<script setup lang="ts">
// Components
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import List from '~/components/app/consultation/list.vue'
import Entry from '~/components/app/consultation/entry.vue'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { ConsultationSchema, type ConsultationFormData } from '~/schemas/consultation.schema'

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

// Services
import { getList, getDetail } from '~/services/consultation.service'
import { getValueLabelList } from '~/services/unit.service'

// Models
import type { Encounter } from '~/models/encounter'

// Props
interface Props {
  encounter: Encounter
}
const props = defineProps<Props>()

let units = ref<{ value: string; label: string }[]>([])
const title = ref('')

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getMyList,
} = usePaginatedList({
  fetchFn: async ({ page, search }) => {
    const result = await getList({ 'encounter-id': props.encounter.id, includes: 'encounter,dstUnit', search, page })
    if (result.success) {
      data.value = result.body.data;
    }
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'consultation',
})

const headerPrep: HeaderPrep = {
  title: 'Konsultasi',
  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 = {
        encounter_id: props.encounter.id,
        date: today.toISOString().slice(0, 10),
        unit_id: 0,
        problem: '',
      }
      recId.value = 0
      isFormEntryDialogOpen.value = true
      isReadonly.value = false
    },
  },
}

const today = new Date()

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:
      isRecordConfirmationOpen.value = true
      break
  }
})

onMounted(async () => {
  await getMyList()
  units.value = await getValueLabelList()
})
</script>

<template>
  <Header
    v-model="searchInput"
    :prep="headerPrep"
    :ref-search-nav="headerPrep.refSearchNav"
    @search="handleSearch"
    class="mb-4 xl:mb-5"
  />
  <List :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />

  <Dialog v-model:open="isFormEntryDialogOpen" :title="recItem?.id ? 'Edit Konsultasi' : 'Tambah Konsultasi'" size="xl" prevent-outside>
    <Entry
      :schema="ConsultationSchema"
      :values="recItem"
      :encounter_id="props.encounter.id"
      :units="units"
      :is-loading="isProcessing"
      :is-readonly="isReadonly"
      @submit="
        (values: ConsultationFormData | Record<string, any>, resetForm: () => void) => {
          if (recId > 0) {
            handleActionEdit(recId, values, getMyList, resetForm, toast)
            return
          }
          handleActionSave(values, getMyList, resetForm, toast)
        }
      "
      @cancel="handleCancelForm"
    />
  </Dialog>

  <!-- Record Confirmation Modal -->
   {{ isRecordConfirmationOpen }}
  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getMyList, 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>
