<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 { getDetail, update } from '~/services/prb.service'
import type { Prb } from '~/models/prb'
import ActionDialog from '~/components/pub/my-ui/nav-footer/ba-su.vue'

import { toast } from '~/components/pub/ui/toast'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import { PrbSchema } from '~/schemas/prb.schema'
import { formatDateYyyyMmDd } from '~/lib/date'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import { getList, remove } from '~/services/prb.service'
import { handleActionEdit } from '~/handlers/prb.handler'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/data/types'
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: 'prb',
})
// #endregion

// #region State & Computed
const router = useRouter()
const inputForm = ref<ExposedForm<any> | null>(null)
const Prb = 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)}
    Prb.value = responseData
    inputForm.value?.setValues(responseData)
  }
})
// #endregion

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

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

async function composeFormData(): Promise<Prb> {
  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 Program Rujuk Balik</div>
  <AppPrbEntry
    ref="inputForm"
    :schema="PrbSchema"
    :initial-values="initialValues"
    :is-bpjs="isBpjs"
  />
  
  <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>
