<script setup lang="ts">
// Components
import AppViewPatient from '~/components/app/patient/view-patient.vue'

// Types
import type { DataTableLoader } from '~/components/pub/my-ui/data-table/type'
import type { PatientEntity } from '~/models/patient'

// Handlers
import {
  patients,
  selectedPatient,
  selectedPatientObject,
  paginationMeta,
  getPatientsList,
  getPatientCurrent,
  getPatientByIdentifierSearch,
} from '~/handlers/patient.handler'

const props = defineProps<{
  id: number
  formType: string
}>()

const openPatient = ref(false)
const isLoading = reactive<DataTableLoader>({
  isTableLoading: false,
})

const division = {
  msg: {
    placeholder: 'Pilih Divisi',
    search: 'Cari Divisi',
    empty: 'Divisi tidak ditemukan',
  },
}

const items = ref([{ value: '1', label: 'Division 1', code: 'DIV1' }])

const schema = {}

function handleSavePatient() {
  selectedPatientObject.value = null
  setTimeout(() => {
    getPatientCurrent(selectedPatient.value)
  }, 150)
}

function toKebabCase(str: string): string {
  return str.replace(/_/g, '-').toLowerCase()
}

function toNavigateSep(values: any) {
  const queryParams = new URLSearchParams()
  Object.keys(values).forEach((field) => {
    if (values[field]) {
      queryParams.append(toKebabCase(field), values[field])
    }
  })
  navigateTo('/integration/bpjs/sep/add' + `?${queryParams.toString()}`)
}

function onSubmit(values: any, resetForm: () => void) {
  console.log('submit', values)
  resetForm()
}

function onCancel(resetForm: () => void) {
  console.log('cancel')
  resetForm()
}

function onClick(e: 'search' | 'add' | 'add-sep', formValues?: any) {
  console.log('click', e)
  if (e === 'search') {
    getPatientsList({ 'page-size': 10, includes: 'person' }).then(() => {
      openPatient.value = true
    })
  } else if (e === 'add') {
    navigateTo('/client/patient/add')
  } else if (e === 'add-sep') {
    selectedPatientObject.value = {} as PatientEntity
    console.log('formValues', formValues)
    toNavigateSep({ resource: 'encounter', is_service: 'false', ...formValues })
  }
}

provide('table_data_loader', isLoading)
</script>

<template>
  <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg xl:text-xl">
    <Icon
      name="i-lucide-user"
      class="me-2"
    />
    <span class="font-semibold">{{ props.formType }}</span>
    Kunjungan
  </div>

  <AppEncounterEntryForm
    :division="division"
    :items="items"
    :schema="schema"
    :selected-patient-object="selectedPatientObject"
    @click="onClick"
    @submit="onSubmit"
    @cancel="onCancel"
  />
  <AppSepSmallEntry v-if="props.id" />

  <AppViewPatient
    v-model:open="openPatient"
    v-model:selected="selectedPatient"
    :patients="patients"
    :pagination-meta="paginationMeta"
    @fetch="
      (value) => {
        if (value.search && value.search.length >= 3) {
          // Use identifier search for specific searches (NIK, RM, etc.)
          getPatientByIdentifierSearch(value.search)
        } else {
          // Use regular search for general searches
          getPatientsList({ ...value, 'page-size': 10, includes: 'person' })
        }
      }
    "
    @save="handleSavePatient"
  />
</template>
