<script setup lang="ts">
import { useRouter } from 'vue-router'
import type { Patient, genPatientProps } from '~/models/patient'
import type { ExposedForm } from '~/types/form'
import type { PatientBase } from '~/models/patient'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import { genPatient } from '~/models/patient'
import { PatientSchema } from '~/schemas/patient.schema'
import { PersonAddressRelativeSchema } from '~/schemas/person-address-relative.schema'
import { PersonAddressSchema } from '~/schemas/person-address.schema'
import { PersonContactListSchema } from '~/schemas/person-contact.schema'
import { PersonFamiliesSchema } from '~/schemas/person-family.schema'
import { ResponsiblePersonSchema } from '~/schemas/person-relative.schema'
import { uploadAttachment } from '~/services/patient.service'
import { getDetail, update } from '~/services/vaccine-data.service'
import type { VaccineData } from '~/models/vaccine-data'
import ActionDialog from '~/components/pub/my-ui/nav-footer/ba-su.vue'

import { toast } from '~/components/pub/ui/toast'
import { withBase } from '~/models/_base'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import { VaccineDataSchema } from '~/schemas/vaccine-data.schema'
import { formatDateYyyyMmDd } from '~/lib/date'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import { getList, remove } from '~/services/vaccine-data.service'
import { handleActionEdit, handleActionSave } from '~/handlers/vaccine-data.handler'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/data/types'
import { formatDateToDatetimeLocal } from '~/lib/utils'

// #region Props & Emits
const props = withDefaults(defineProps<{
  callbackUrl?: string
  isBpjs?: boolean
}>(), {
  isBpjs: false,
})

// form related state
const { data, isLoading, paginationMeta, searchInput, handlePageChange, handleSearch, fetchData } = usePaginatedList({
  fetchFn: (params) => getList({ ...params, includes: 'specialist,subspecialist,doctor-employee-person', }),
  entityName: 'vaccine-data',
})
// #endregion

// #region State & Computed
const route = useRoute()
const router = useRouter()
const encounterId = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0
const VaccineDataId = typeof route.params.surgery_report_id == 'string' ? parseInt(route.params.surgery_report_id) : 0

const inputForm = ref<ExposedForm<any> | null>(null)
const VaccineData = ref({})
const isConfirmationOpen = ref(false)
const selectedOperativeAction = ref<any>(null)

const isSepDialogOpen = ref(false)
provide("isSepDialogOpen", isSepDialogOpen);
// #endregion

// #region Lifecycle Hooks
onMounted(async () => {
  const result = await getDetail(VaccineDataId)
  if (result.success) {
    const responseData = {...result.body.data, date: formatDateYyyyMmDd(result.body.data.date)}
    VaccineData.value = responseData
    inputForm.value?.setValues(responseData)
  }
})
// #endregion

// #region Functions
function goBack() {
  router.go(-1)
}

async function handleConfirmAdd() {
  const response = await handleActionSave(
    await composeFormData(),
    () => { },
    () => { },
    toast,
  )
  goBack()
}

async function composeFormData(): Promise<VaccineData> {
  const [input,] = await Promise.all([
    inputForm.value?.validate(),
  ])

  const results = [input]
  const allValid = results.every((r) => r?.valid)

  // exit, if form errors happend during validation
  if (!allValid) return Promise.reject('Form validation failed')

  const formData = input?.values
  formData.encounter_id = encounterId
  return new Promise((resolve) => resolve(formData))
}
// #endregion region

// #region Utilities & event handlers
async function handleActionClick(eventType: string) {
  if (eventType === 'submit') {
    isConfirmationOpen.value = true
  }

  if (eventType === 'back') {
    if (props.callbackUrl) {
      await navigateTo(props.callbackUrl)
      return
    }

    goBack()
  }
}

function handleCancelAdd() {
  isConfirmationOpen.value = false
}
// #endregion

// #region Watchers
// #endregion

const initialValues = {
  a1: "",
  a2: formatDateToDatetimeLocal(new Date()),
}
</script>

<template>
  <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg font-semibold xl:text-xl">Update Data Vaksin</div>
  <AppVaccineDataEntry
    ref="inputForm"
    :schema="VaccineDataSchema"
    :initial-values="initialValues"
    :is-bpjs="isBpjs"
  />
  
  <div class="my-2 flex justify-end py-2">
    <Action @click="handleActionClick" />
  </div>

  <Confirmation
    v-model:open="isConfirmationOpen"
    title="Simpan Data"
    message="Apakah Anda yakin ingin menyimpan data ini?"
    confirm-text="Simpan"
    @confirm="handleConfirmAdd"
    @cancel="handleCancelAdd"
  />
</template>

<style scoped>
/* component style */
</style>
