<script setup lang="ts">
// Composables
import { useQueryCRUDMode } from '~/composables/useQueryCRUD'
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { toast } from '~/components/pub/ui/toast'

// Pub components
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'

// Refs / src
import { type Device } from '~/models/device'
import { getList as getDeviceList } from '~/services/device.service'

// Device order things
import { getDetail, remove, submit } from '~/services/device-order.service'
import EntryForm from '~/components/app/device-order/entry-form.vue'

// Items
import {
  getList as getItemList,
  create as createItem,
  update as updateItem,
} from '~/services/device-order-item.service'
import {
  recId,
  recAction,
  recItem,
  handleActionRemove,
} from '~/handlers/device-order-item.handler'
import { genDeviceOrderItem, type DeviceOrderItem } from '~/models/device-order-item'
import ItemListEntry from '~/components/app/device-order-item/list-entry.vue'
import ItemEntry from '~/components/app/device-order-item/entry-form.vue'

// Header
const headerPrep: HeaderPrep = {
  title: 'Tambah Order Alkes',
  icon: 'i-lucide-box',
}

// Device order things
const { getQueryParam } = useQueryParam()
const rawId = getQueryParam('id')
const id = typeof rawId === 'string' ? parseInt(rawId) : 0
const dataRes = await getDetail(id, { includes: 'doctor,doctor-employee,doctor-employee-person' })
const data = ref(dataRes.body?.data || null)
const devices = ref<Device[]>([])

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

// Items
const {
    data: items,
    isLoading,
    fetchData: getDeviceOrderItems,
  } = usePaginatedList({
    fetchFn: async (params: any) => {
      const result = await getItemList({
        'device-order-id': id,
        includes: 'device',
        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 selectedItem = ref<DeviceOrderItem>(genDeviceOrderItem())
const isItemDetailDialogOpen = ref(false)
const isItemEntryDialogOpen = ref(false)
const isItemDelConfirmDialogOpen = ref(false)

selectedItem.value.deviceOrder_id = id

// Last navs
const { backToList } = useQueryCRUDMode()

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

watch([recId, recAction], () => {
  let item: DeviceOrderItem | null
  switch (recAction.value) {
    case ActionEvents.showDetail:
      item = pickItem()
      if (item) {
        isItemDetailDialogOpen.value = true
      }
      break
    case ActionEvents.showEdit:
      item = pickItem()
      if (item) {
        isItemEntryDialogOpen.value = true
        getDevices('', item.device_code)
      }
      break
    case ActionEvents.showConfirmDelete:
      isItemDelConfirmDialogOpen.value = true
      break
  }
})

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

// Functions
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 removeOrder() {
  const res = await remove(id)
  if (res.success) {
    backToList()
  }
}

async function submitOrder() {
  const res = await submit(id)
  if (res.success) {
    backToList()
  }
}

function addItem() {
  isItemEntryDialogOpen.value = true
}

async function getDevices(value: string, code?: string) {
  const res = await getDeviceList({ 'search': value, 'code': code })
  if (res.success) {
    devices.value = res.body.data
  } else {
    devices.value = []
  }
}

function pickItem(): DeviceOrderItem | null {
  const item = items.value.find(item => item.id === recId.value)
  selectedItem.value = item
  return item
}

async function saveItem() {
  let res: any;
  if(!selectedItem.value.id) {
    res = await createItem(selectedItem.value)
  } else {
    res = await updateItem(selectedItem.value.id, selectedItem.value)
  }
  if (res.success) {
    toast({ title: 'Berhasil', description: 'Resep telah di ajukan', variant: 'default' })
    getDeviceOrderItems()
    isItemEntryDialogOpen.value = false
    selectedItem.value = genDeviceOrderItem()
  }
}

</script>

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

  <EntryForm :data="data" @add="addItem" />

  <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="data"
    @confirm="removeOrder()"
  />

  <!-- Confirm submit -->
  <RecordConfirmation
    v-model:open="isSubmitConfirmationOpen"
    customTitle="Ajukan Order"
    customMessage="Akan dilakukan pengajuan order alat kesehatan"
    customConfirmText="Ajukan"
    :record="data"
    @confirm="submitOrder"
    @cancel=""
  />

  <!-- Item entry -->
  <Dialog
    v-model:open="isItemEntryDialogOpen"
    title="Item Order"
    size="lg"
    prevent-outside
  >
    <ItemEntry
      :data="selectedItem"
      :devices="devices"
      @close="isItemEntryDialogOpen = false"
      @save="saveItem"
      @update:searchText="getDevices"
    />
  </Dialog>

  <RecordConfirmation
    v-model:open="isItemDelConfirmDialogOpen"
    action="delete"
    size="md"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getDeviceOrderItems, toast)"
    @cancel=""
  >
    <DE.Block mode="preview" label-size="small">
      <DE.Cell>
        <DE.Label>Nama</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.device.name }}
        </DE.Field>
      </DE.Cell>
      <DE.Cell>
        <DE.Label>Dosis</DE.Label>
        <DE.Colon />
        <DE.Field>
          {{ recItem.quantity }}
        </DE.Field>
      </DE.Cell>
    </DE.Block>
  </RecordConfirmation>
</template>
