<script setup lang="ts">
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import List from './list.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import { ActionEvents, type HeaderPrep, type RefSearchNav } from '~/components/pub/my-ui/data/types'
import { getList } from '~/services/vclaim-monitoring-visit.service'
import type { VclaimSepData } from '~/models/vclaim'
import type { PaginationMeta } from '~/components/pub/my-ui/pagination/pagination.type'
import { defaultQuerySchema, defaultQueryParams } from '~/composables/usePaginatedList'

interface Props {
  title: string
  chooseFn: (inputValue: string) => void
}
const props = defineProps<Props>()
const isSepDialogOpen = inject('isSepDialogOpen') as Ref<boolean>;
const handleToggleSepDialog = () => isSepDialogOpen.value = !isSepDialogOpen.value

const data = ref<VclaimSepData[]>([])// Search model with debounce
  const searchInput = ref('')
  const debouncedSearch = refDebounced(searchInput, 500) // 500ms debounce
// const paginationMeta = reactive<PaginationMeta>({
//   recordCount: 0,
//   page: 1,
//   pageSize: 10,
//   totalPage: 5,
//   hasNext: false,
//   hasPrev: false,
// })
// // URL state management
// const queryParams = useUrlSearchParams('history', {
//   initialValue: defaultQueryParams,
//   removeFalsyValues: true,
// })
// const params = computed(() => {
//   const result = defaultQuerySchema.safeParse(queryParams)
//   return result.data || defaultQueryParams
// })

const recId = ref<string>(``)
const recAction = ref<string>(``)
const recItem = ref<any>({})
const timestamp = ref<any>({})
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('timestamp', timestamp)

const headerPrep: HeaderPrep = {
  title: props.title,
  icon: 'i-lucide-clipboard-list',
}
const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
  },
  onInput: (val: string) => {
    searchInput.value = val
  },
  onClear: () => {
    searchInput.value = ''
  },
}


async function getMonitoringVisitMappers() {
  data.value = []
  const tempArr: VclaimSepData[] = []

  const result = await getList({
    serviceType: 1,
    search: debouncedSearch.value,
  })

  if (result && result.success && result.body) {
    const visitsRaw = result.body?.response?.sep || []

    visitsRaw.forEach((result: any) => {
      // Format pelayanan: "R.Inap" -> "Rawat Inap", "1" -> "Rawat Jalan", dll
      let serviceType = result.jnsPelayanan || '-'
      if (serviceType === 'R.Inap') {
        serviceType = 'Rawat Inap'
      } else if (serviceType === '1' || serviceType === 'R.Jalan') {
        serviceType = 'Rawat Jalan'
      }

      tempArr.push({
        letterDate: result.tglSep || '-',
        letterNumber: result.noSep || '-',
        serviceType: serviceType,
        flow: '-',
        medicalRecordNumber: '-',
        patientName: result.nama || '-',
        cardNumber: result.noKartu || '-',
        controlLetterNumber: result.noRujukan || '-',
        controlLetterDate: result.tglPlgSep || '-',
        clinicDestination: result.poli || '-',
        attendingDoctor: '-',
        diagnosis: result.diagnosa || '-',
        careClass: result.kelasRawat || '-',
      })
    })
    data.value = tempArr
  }
}
// Handle pagination page change
// function handlePageChange(page: number) {
//   // Update URL params - this will trigger watcher
//   queryParams['page-number'] = page
// }

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


watch([recId, recAction, timestamp], () => {
  switch (recAction.value) {
    case ActionEvents.showProcess:
      props.chooseFn(recItem.value.cardNumber)
      handleToggleSepDialog()
      break
  }
})

watch(debouncedSearch, () => {
  getMonitoringVisitMappers()
})
</script>

<template>
  <div class="">
    <Dialog v-model:open="isSepDialogOpen" title="" size="full">
      <Header 
        v-model="searchInput"
        :prep="headerPrep"
        :ref-search-nav="refSearchNav" />
      <List :data="data" />
    </Dialog>
  </div>
</template>
