<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'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'
import { config } from './diagnosis-list-cfg'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { DiagnoseSrcSchema, type DiagnoseSrcFormData } from '~/schemas/diagnose-src.schema'

// Services
import { getList, getDetail } from '~/services/diagnose-src.service'

const title = ref('')

interface Props {
  processFn: (input: unknown) => void
}
const props = defineProps<Props>()

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getItemList,
} = usePaginatedList({
  fetchFn: async (params: any) => {
    const result = await getList({
      search: params.search,
      sort: 'createdAt:desc',
      'page-number': params['page-number'] || 0,
      'page-size': params['page-size'] || 10,
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'diagnose-src',
})

const headerPrep: HeaderPrep = {
  title: 'Daftar Diagnosis',
  icon: 'i-lucide-microscope',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (val: string) => {
      searchInput.value = val
    },
    onClick: () => {},
    onClear: () => {},
  },
}

const recId = ref<string>(``)
const recAction = ref<string>(``)
const recItem = ref<any>({})
provide('md_rec_id', recId)
provide('md_rec_action', recAction)
provide('md_rec_item', recItem)
provide('table_data_loader', isLoading)

const isModalOpen = inject(`isMedicalDiagnosisPickerDialogOpen`) as Ref<boolean>

watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showProcess:
      props.processFn({
        id: recId.value,
        code: recItem.value.code,
        name: recItem.value.name,
      })
      isModalOpen.value = false
      break
  }
})

onMounted(async () => {
  await getItemList()
})
</script>

<template>
  <Dialog v-model:open="isModalOpen" title="" size="xl">
    <Header
      v-model="searchInput"
      :prep="headerPrep"
      :ref-search-nav="headerPrep.refSearchNav"
      @search="handleSearch"
      class=""
    />
    <AppDiagnoseSrcList
      :data="data"
      :pagination-meta="paginationMeta"
      :table-config="config"
      @page-change="handlePageChange"
    />
  </Dialog>
</template>
