<script setup lang="ts">
import { usePaginatedList } from '~/composables/usePaginatedList'

import { toast } from '~/components/pub/ui/toast'
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  handleActionRemove,
  handleActionSave,
} from '~/handlers/prescription.handler'

// Services
import { getList, getDetail } from '~/services/prescription.service'
import List from '~/components/app/prescription/list.vue'
import type { Prescription } from '~/models/prescription'
import { submit } from '~/services/prescription.service'
import type { ToastFn } from '~/handlers/_handler'

const props = defineProps<{
  encounter_id: number
}>()

const route = useRoute()
const { setQueryParams } = useQueryParam()

const title = ref('')
const isSubmitConfirmationOpen = ref(false)

const plainEid = route.params.id
const encounter_id = (plainEid && typeof plainEid == 'string') ? parseInt(plainEid) : 0

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  fetchData: getMyList,
} = usePaginatedList<Prescription>({
  fetchFn: async ({ page, search }) => {
    const result = await getList({
      search,
      page,
      'encounter-id': encounter_id,
      includes: 'doctor,doctor-employee,doctor-employee-person',
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'prescription'
})

const headerPrep: HeaderPrep = {
  title: 'Order Obat',
  icon: 'i-lucide-box',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (value: string) => {
      searchInput.value = value
    },
    onClick: () => {},
    onClear: () => {},
  },
  addNav: {
    label: 'Tambah',
    icon: 'i-lucide-plus',
    onClick: () => {
      recItem.value = null
      recId.value = 0
      isFormEntryDialogOpen.value = true
      isReadonly.value = false
    },
  },
}

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)

const getMyDetail = async (id: number | string) => {
  const result = await getDetail(id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    recItem.value = currentValue
    isFormEntryDialogOpen.value = true
  }
}

// Watch for row actions when recId or recAction changes
watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      getMyDetail(recId.value)
      title.value = 'Detail Konsultasi'
      isReadonly.value = true
      break
    case ActionEvents.showEdit:
      getMyDetail(recId.value)
      title.value = 'Edit Konsultasi'
      isReadonly.value = false
      break
    case ActionEvents.showConfirmDelete:
      break
  }
})

watch([isFormEntryDialogOpen], async () => {
  if (isFormEntryDialogOpen.value) {
    isFormEntryDialogOpen.value = false;
    const saveResp = await handleActionSave({ encounter_id }, getMyList, () =>{}, toast)
    if (saveResp.success) {
      setQueryParams({
        'mode': 'entry',
        'id': saveResp.body?.data?.id.toString()
      })
    }
  }
})

function confirmCancel(data: Prescription) {
  recId.value = data.id
  recItem.value = data
  isRecordConfirmationOpen.value = true
}

function goToEdit(data: Prescription) {
  setQueryParams({
    'mode': 'entry',
    'id': data.id.toString()
  })
  recItem.value = data
}

function confirmSubmit(data: Prescription) {
  recId.value = data.id
  recItem.value = data
  isSubmitConfirmationOpen.value = true
}

async function handleActionSubmit(id: number, refresh: () => void, toast: ToastFn) {
  const result = await submit(id)
  if (result.success) {
    toast({ title: 'Berhasil', description: 'Resep telah di ajukan', variant: 'default' })
    setTimeout(refresh, 300)
  } else {
    toast({ title: 'Gagal', description: 'Gagal menjalankan perintah', variant: 'destructive' })
  }
}
</script>

<template>
  <Header :prep="{ ...headerPrep }" />
  <List
    v-if="!isLoading.dataListLoading"
    :data="data"
    :pagination-meta="paginationMeta"
    @cancel="confirmCancel"
    @edit="goToEdit"
    @submit="confirmSubmit"
  />

  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getMyList, toast)"
    @cancel=""
  >
  </RecordConfirmation>

  <RecordConfirmation
    v-model:open="isSubmitConfirmationOpen"
    action="delete"
    customTitle="Ajukan Resep"
    customMessage="Proses akan mengajukan resep ini untuk diproses lebih lanjut. Lanjutkan?"
    customConfirmText="Ajukan"
    :record="recItem"
    @confirm="() => handleActionSubmit(recId, getMyList, toast)"
    @cancel=""
  >
  </RecordConfirmation>
</template>
