<script setup lang="ts">
import { type HeaderPrep, ActionEvents } from '~/components/pub/my-ui/data/types'
import Nav from '~/components/pub/my-ui/nav-footer/ba-de-su.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import * as DE from '~/components/pub/my-ui/doc-entry'
import { toast } from '~/components/pub/ui/toast'

import { useQueryCRUDMode } from '~/composables/useQueryCRUD'

// Medicine
import { type Medicine } from '~/models/medicine'
import { getList as getMedicineList } from '~/services/medicine.service'

// Prescription
import { getDetail } from '~/services/prescription.service'
// import Detail from '~/components/app/prescription/detail.vue'
import Entry from '~/components/app/prescription/entry.vue'
import { remove, submit } from '~/services/prescription.service'

// Prescription items
import {
  getList as getItemList,
  create as createItem,
  update as updateItem,
} from '~/services/prescription-item.service'
import {
  recId,
  recAction,
  recItem,
  isRecordConfirmationOpen,
  handleActionRemove,
} from '~/handlers/prescription-item.handler'

import { type PrescriptionItem, genPrescriptionItem } from '~/models/prescription-item'
import { type MedicinemixItem } from '~/models/medicinemix-item';
import ItemListEntry from '~/components/app/prescription-item/list-entry.vue'
import NonMixItemEntry from '~/components/app/prescription-item/non-mix-entry.vue'
import MixItemEntry from '~/components/app/prescription-item/mix-entry.vue'

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

// Prescriptions 
const isSubmitConfirmationOpen = ref(false)
const isDeleteConfirmationOpen = ref(false)

// Prescription Items
const isItemDetailDialogOpen = ref(false)

// Prescription
const { getQueryParam } = useQueryParam()
const rawId = getQueryParam('id')
const id = typeof rawId === 'string' ? parseInt(rawId) : 0
const dataRes = await getDetail(id, { includes: 'encounter,doctor,doctor-employee,doctor-employee-person' })
const data = ref(dataRes.body?.data || null)

// Prescription Items
const getItemsOpt = { 'prescription-id': id, includes: 'medicine,medicine-medicineForm,medicineMix' }
const {
  data: items,
  isLoading,
  fetchData: getPrescriptionItems,
} = usePaginatedList({
  fetchFn: async (params: any) => {
    const result = await getItemList({
      ...getItemsOpt,
      search: params.search,
      sort: 'createdAt:asc',
      'page-number': params['page-number'] || 0,
      'page-size': params['page-size'] || 10,
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'division',
})


// const items = ref<PrescriptionItem[]>([])
const mixItem = ref<PrescriptionItem>(genPrescriptionItem())
const medicinemixItems = ref<MedicinemixItem[]>([])
const nonMixItem = ref<PrescriptionItem>(genPrescriptionItem())

mixItem.value.prescription_id = id
nonMixItem.value.prescription_id = id

const { backToList } = useQueryCRUDMode()

const headerPrep: HeaderPrep = {
  title: 'Pembuatan Order Obat / Resep',
  icon: 'i-lucide-box',
}

const mixDialogOpenStatus = ref(false)
const nonMixDialogOpenStatus = ref(false)
const medicines = ref<Medicine[]>([])

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

watch([recId, recAction], () => {
  let item: PrescriptionItem | null
  switch (recAction.value) {
    case ActionEvents.showDetail:
      item = pickItem()
      if (item) {
        isItemDetailDialogOpen.value = true
      }
      break
    case ActionEvents.showEdit:
      item = pickItem()
      if (item) {
        if(item.isMix) {
          mixDialogOpenStatus.value = true
        } else {
          nonMixDialogOpenStatus.value = true
        }
        getMedicines('', item.medicine_code)
      }
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

onMounted(async () => {
  await getPrescriptionItems()
})

function navClick(type: 'back' | 'delete' | 'draft' | 'submit') {
  if (type === 'back') {
    backToList()
  } else if (type === 'delete') {
    isDeleteConfirmationOpen.value = true
  } else if (type === 'submit') {
    isSubmitConfirmationOpen.value = true
  }
}

async function removePrescription() {
  const res = await remove(id)
  if (res.success) {
    backToList()
  }
  // handleActionRemove(recId.value, getItems, toast)
}

async function submitPrescription() {
  const res = await submit(id)
  if (res.success) {
    backToList()
  }
  // handleActionRemove(recId.value, getItems, toast)
}

function addItem(mode: 'mix' | 'non-mix') {
  if (mode === 'mix') {
    mixDialogOpenStatus.value = true
  } else if (mode === 'non-mix') {
    nonMixDialogOpenStatus.value = true
  }
}

async function saveMix() {
  const res = await createItem(mixItem.value)
  if (res.success) {
    toast({ title: 'Berhasil', description: 'Resep telah di ajukan', variant: 'default' })
    getPrescriptionItems()
    mixDialogOpenStatus.value = false
  }
}

async function saveNonMix() {
  let res: any;
  if(!nonMixItem.value.id) {
    res = await createItem(nonMixItem.value)
  } else {
    res = await updateItem(nonMixItem.value.id, nonMixItem.value)
  }
  if (res.success) {
    toast({ title: 'Berhasil', description: 'Resep telah di ajukan', variant: 'default' })
    getPrescriptionItems()
    nonMixDialogOpenStatus.value = false
  }
}

async function getMedicines(value: string, code?: string) {
  const res = await getMedicineList({ 'search': value, 'includes': 'medicineForm', 'code': code })
  if (res.success) {
    medicines.value = res.body.data
  } else {
    medicines.value = []
  }
}

function pickItem(): PrescriptionItem | null {
  const item = items.value.find(item => item.id === recId.value)
  if (!item) {
    return null
  }
  if(item.isMix) {
    mixItem.value = item
  } else {
    nonMixItem.value = item
  }
  return item
}
</script>

<template>
  <Header
    :prep="headerPrep"
    :ref-search-nav="headerPrep.refSearchNav"
    class="mb-4 xl:mb-5"
  />

  <Entry :data="data" />

  <!-- <div class="mb-8">
    <Button>
      <Icon name="i-lucide-check" />
      Simpan
    </Button>
  </div> -->

  <ItemListEntry
    :data="items"
    @add="addItem"/>

  <Separator class="my-5" />

  <div class="w-full flex justify-center">
    <Nav @click="navClick" />
  </div>

  <!-- Confirm delete -->
  <RecordConfirmation
    v-model:open="isDeleteConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="removePrescription()"
  />

  <!-- Confirm submit -->
  <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="submitPrescription"
    @cancel=""
  />

  <!-- Mix form -->
  <Dialog
    v-model:open="mixDialogOpenStatus"
    title="Pembuatan Racikan"
    size="lg"
    prevent-outside
  >
    <MixItemEntry
      :data="mixItem"
      :items="medicinemixItems"
      :medicines="medicines"
      @close="mixDialogOpenStatus = false"
      @save="saveMix"
      @update:searchText="getMedicines"
    />
  </Dialog>

  <!-- Non mix form -->
  <Dialog
    v-model:open="nonMixDialogOpenStatus"
    title="Pembuatan Non Racikan"
    size="lg"
    prevent-outside
  >
    <NonMixItemEntry
      :data="nonMixItem"
      :medicines="medicines"
      @close="mixDialogOpenStatus = false"
      @save="saveNonMix"
      @update:searchText="getMedicines"
    />
  </Dialog>

  <!-- Detail item -->
  <Dialog
    v-model:open="isItemDetailDialogOpen"
    title="Detail Obat"
    size="lg"
    prevent-outside
  >
    <DE.Block mode="preview" label-size="small">
      <DE.Cell>
        <DE.Label>Nama</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.medicine.name }}
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Dosis</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.dose }}
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Sediaan</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.medicine.medicineForm.name }}
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Jumlah</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.quantity }}
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Cara Pakai</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.Usage }}
        </DE.Field>
      </DE.Cell>
    </DE.Block>
  </Dialog>

  <!-- Confirm delete items -->
  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getPrescriptionItems, toast)"
    @cancel=""
  >
    <template #default="{ record }">
      <div class="text-sm">
        <p>
          <strong>ID:</strong>
          {{ record?.id }}
        </p>
        <p v-if="record?.name">
          <strong>Nama:</strong>
          {{ record.name }}
        </p>
        <p v-if="record?.code">
          <strong>Kode:</strong>
          {{ record.code }}
        </p>
      </div>
    </template>
  </RecordConfirmation>
</template>
