<script setup lang="ts">
import type { DataTableLoader } from '~/components/pub/my-ui/data-table'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'

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

const isOpen = ref(false)
const data = ref([])
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 = {}

async function getPatientList() {
  isLoading.isTableLoading = true
  const resp = await xfetch('/api/v1/patient')
  if (resp.success) {
    data.value = (resp.body as Record<string, any>).data
  }
  isLoading.isTableLoading = false
}

onMounted(() => {
  getPatientList()
})

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') {
    console.log('search')
  } else if (e === 'add') {
    navigateTo('/client/patient/add')
  } else if (e === 'add-sep') {
    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"
    @click="onClick"
    @submit="onSubmit"
    @cancel="onCancel"
  />
  <AppSepSmallEntry v-if="props.id" />

  <Dialog
    v-model:open="isOpen"
    title="Cari Pasien"
    size="xl"
    prevent-outside
  >
    <AppPatientPicker :data="data" />
  </Dialog>
</template>
