<script setup lang="ts">
import Header from '~/components/pub/my-ui/nav-header/prep.vue'

import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isRecordConfirmationOpen,
  handleActionSave,
  handleActionRemove,
} from '~/handlers/mcu-order.handler'

// Apps
import { getList, getDetail } from '~/services/mcu-order.service'
import List from '~/components/app/mcu-order/list.vue'
import type { McuOrder } from '~/models/mcu-order'

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

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

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

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getMyList,
} = usePaginatedList<McuOrder>({
  fetchFn: async ({ page, search }) => {
    const result = await getList({
      search,
      page,
      'scope-code': "rad",
      'encounter-id': encounter_id,
      includes: 'doctor,doctor-employee,doctor-employee-person',
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'mcu-order'
})

const headerPrep: HeaderPrep = {
  title: 'Order Radiologi',
  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
      addTrigger.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
    addTrigger.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 Order Radiologi'
      isReadonly.value = true
      break
    case ActionEvents.showEdit:
      getMyDetail(recId.value)
      title.value = 'Edit Order Radiologi'
      isReadonly.value = false
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

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

onMounted(async () => {
})

function cancel(data: McuOrder) {
  recId.value = data.id
  recItem.value = data
  isRecordConfirmationOpen.value = true
}

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

function submit(data: McuOrder) {
}
</script>

<template>
  <Header :prep="{ ...headerPrep }" />

  <List
    v-if="!isLoading.dataListLoading"
    :data="data"
    :pagination-meta="paginationMeta"
    @cancel="cancel"
    @edit="edit"
    @submit="submit"
  />

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