<script setup lang="ts">
import { useRouter } from 'vue-router'
import type { ExposedForm } from '~/types/form'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import { getDetail, update } from '~/services/vaccine-data.service'
import type { VaccineData } from '~/models/vaccine-data'

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 { formatDateToDatetimeLocal } from '~/lib/utils'

// #region Props & Emits
const props = withDefaults(defineProps<{ 
  encounter_id: number
  callbackUrl?: string
  record_id: number 
  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 router = useRouter()
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(props.record_id)
  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 = props.encounter_id
  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>
