<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 { 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/control-letter.service'

import {
  // for form entry
  isReadonly,
  isProcessing,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  onResetState,
  handleActionSave,
  handleActionEdit,
} from '~/handlers/control-letter.handler'

import { toast } from '~/components/pub/ui/toast'
import { withBase } from '~/models/_base'
import type { Person } from '~/models/person'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import type { ControlLetter } from '~/models/control-letter'
import { ControlLetterSchema } from '~/schemas/control-letter.schema'
import { formatDateYyyyMmDd } from '~/lib/date'

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

// form related state
const controlLetterForm = ref<ExposedForm<any> | null>(null)
// #endregion

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

const isConfirmationOpen = ref(false)
const controlLetter = ref({})

const selectedUnitId = ref<number|null>(null)
const selectedSpecialistId = ref<number|null>(null)
const selectedSubSpecialistId = ref<number|null>(null)
// #endregion

// #region Lifecycle Hooks
onMounted(async () => {
  const result = await getDetail(controlLetterId)
  if (result.success) {
    const responseData = {...result.body.data, date: formatDateYyyyMmDd(result.body.data.date)}
    selectedUnitId.value = responseData?.unit_code
    selectedSpecialistId.value = responseData?.specialist_code
    selectedSubSpecialistId.value = responseData?.subspecialist_code

    controlLetter.value = responseData
    controlLetterForm.value?.setValues(responseData)
  }
})
// #endregion

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

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

async function composeFormData(): Promise<ControlLetter> {
  const [controlLetter,] = await Promise.all([
    controlLetterForm.value?.validate(),
  ])

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

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

  const formData = controlLetter?.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
}

provide("selectedUnitId", selectedUnitId);
provide("selectedSpecialistId", selectedSpecialistId);
provide("selectedSubSpecialistId", selectedSubSpecialistId);
// #endregion

// #region Watchers
// #endregion
</script>

<template>
  <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg font-semibold xl:text-xl">Update Surat Kontrol</div>
  <AppControlLetterEntryForm
    ref="controlLetterForm"
    :schema="ControlLetterSchema"
    :selected-unit-id="selectedUnitId"
    :selected-specialist-id="selectedSpecialistId"
    :selected-sub-specialist-id="selectedSubSpecialistId"
  />
  
  <div class="my-2 flex justify-end py-2">
    <Action :enable-draft="false" @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>
