<script setup lang="ts">
import type { ExposedForm } from '~/types/form';
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import { ResumeSchema } from '~/schemas/resume.schema';
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import { CalendarDate, DateFormatter, getLocalTimeZone } from '@internationalized/date';
import type { DateRange } from 'radix-vue';
import { getPatients } from '~/services/patient.service';
import ActionHistoryDialog from '~/components/app/resume/history-list/action-history-dialog.vue';
import ConsultationHistoryDialog from '~/components/app/resume/history-list/consultation-history-dialog.vue';
import SupportingHistoryDialog from '~/components/app/resume/history-list/supporting-history-dialog.vue';
import FarmacyHistoryDialog from '~/components/app/resume/history-list/farmacy-history-dialog.vue';
import NationalProgramHistoryDialog from '~/components/app/resume/history-list/national-program-history-dialog.vue';

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

})

// form related state
const personPatientForm = ref<ExposedForm<any> | null>(null)
const actionHistoryData = usePaginatedList({
  fetchFn: (params) => getPatients({ ...params, includes: ['person', 'person-Addresses'] }),
  entityName: 'patient',
})
const consultationHistoryData = usePaginatedList({
  fetchFn: (params) => getPatients({ ...params, includes: ['person', 'person-Addresses'] }),
  entityName: 'patient',
})
const supportingHistoryData = usePaginatedList({
  fetchFn: (params) => getPatients({ ...params, includes: ['person', 'person-Addresses'] }),
  entityName: 'patient',
})
const farmacyHistoryData = usePaginatedList({
  fetchFn: (params) => getPatients({ ...params, includes: ['person', 'person-Addresses'] }),
  entityName: 'patient',
})
const nationalProgramServiceHistoryData = usePaginatedList({
  fetchFn: (params) => getPatients({ ...params, includes: ['person', 'person-Addresses'] }),
  entityName: 'patient',
})
// #endregion

// #region State & Computed
const router = useRouter()
const isConfirmationOpen = ref(false)
const isActionHistoryOpen = ref<boolean>(false)
const isConsultationHistoryOpen = ref<boolean>(false)
const isSupportingHistoryOpen = ref<boolean>(false)
const isFarmacyHistoryOpen = ref<boolean>(false)
const isNationalProgramServiceHistoryOpen = ref<boolean>(false)

provide(`isActionHistoryOpen`, isActionHistoryOpen)
provide(`isConsultationHistoryOpen`, isConsultationHistoryOpen)
provide(`isSupportingHistoryOpen`, isSupportingHistoryOpen)
provide(`isFarmacyHistoryOpen`, isFarmacyHistoryOpen)
provide(`isNationalProgramServiceHistoryOpen`, isNationalProgramServiceHistoryOpen)

const defaultDate = {
  start: new CalendarDate(2022, 1, 20),
  end: new CalendarDate(2022, 1, 20).add({ days: 20 }),
}

const actionHistoryDateValue = ref(defaultDate) as Ref<DateRange>
const consultationHistoryDateValue = ref(defaultDate) as Ref<DateRange>
const supportingHistoryDateValue = ref(defaultDate) as Ref<DateRange>
const farmacyHistoryDateValue = ref(defaultDate) as Ref<DateRange>
const nationalProgramServiceSearch = ref<string>('')
const nationalProgramServiceSelectedStatus = ref<string>('all')
// #endregion

// #region Lifecycle Hooks
onMounted(() => {

})
// #endregion

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

async function handleConfirmAdd() {
  // handleActionClick('submit')
  console.log(`tersubmit wak`)
}

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

// #region Utilities & event handlers
async function handleActionClick(eventType: string) {
  if (eventType === 'submit') {
    isConfirmationOpen.value = true
    // const patient: Patient = await composeFormData()
    // let createdPatientId = 0

    // const response = await handleActionSave(
    //   patient,
    //   () => {},
    //   () => {},
    //   toast,
    // )

    // const data = (response?.body?.data ?? null) as PatientBase | null
    // if (!data) return
    // createdPatientId = data.id

    // If has callback provided redirect to callback with patientData
    // if (props.callbackUrl) {
    //   await navigateTo(props.callbackUrl + '?patient-id=' + patient.id)
    //   return
    // }

    // Navigate to patient list or show success message
    // await navigateTo('/outpatient/encounter')
    // return
  }

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

    goBack()
    // handleCancelForm()
  }
}
// #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">Tambah Resume</div>
  <AppResumeAdd 
    ref="personPatientForm"
    :schema="ResumeSchema"
    :resume-arrangement-type="personPatientForm?.values.arrangement"/>
  
  <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"
  />

  <ActionHistoryDialog
    v-model:is-modal-open="isActionHistoryOpen"
    v-model:date-value="actionHistoryDateValue"
    :data="actionHistoryData.data.value"
    :pagination-meta="actionHistoryData.paginationMeta"
    @page-change="actionHistoryData.handlePageChange"
  />

  <p v-if="isConsultationHistoryOpen === true">aaaaaaaaaaaaaaa</p>
  <ConsultationHistoryDialog
    v-model:is-modal-open="isConsultationHistoryOpen"
    v-model:date-value="consultationHistoryDateValue"
    :data="consultationHistoryData.data.value"
    :pagination-meta="consultationHistoryData.paginationMeta"
    @page-change="consultationHistoryData.handlePageChange"
  />

  <SupportingHistoryDialog
    v-model:is-modal-open="isSupportingHistoryOpen"
    v-model:date-value="supportingHistoryDateValue"
    :data="supportingHistoryData.data.value"
    :pagination-meta="supportingHistoryData.paginationMeta"
    @page-change="supportingHistoryData.handlePageChange"
  />

  <FarmacyHistoryDialog
    v-model:is-modal-open="isFarmacyHistoryOpen"
    v-model:date-value="farmacyHistoryDateValue"
    :data="farmacyHistoryData.data.value"
    :pagination-meta="farmacyHistoryData.paginationMeta"
    @page-change="farmacyHistoryData.handlePageChange"
  />

  <NationalProgramHistoryDialog
    v-model:is-modal-open="isNationalProgramServiceHistoryOpen"
    v-model:search-value="nationalProgramServiceSearch"
    v-model:status-value="nationalProgramServiceSelectedStatus"
    :data="nationalProgramServiceHistoryData.data.value"
    :pagination-meta="nationalProgramServiceHistoryData.paginationMeta"
    @page-change="nationalProgramServiceHistoryData.handlePageChange"
  />
</template>
