<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 { toast } from '~/components/pub/ui/toast'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import { KfrSchema, } from '~/schemas/kfr.schema'
import { handleActionSave, handleActionEdit } from '~/handlers/kfr.handler'
import { getDetail } from '~/services/kfr.service';

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

})

// form related state
const route = useRoute()
const mode = computed(() => props.record_id ? `edit` : `add`)
const inputForm = ref<ExposedForm<any> | null>(null)
// #endregion

// #region State & Computed
const router = useRouter()
const isConfirmationOpen = ref(false)
// #endregion

// #region Lifecycle Hooks
onMounted(() => {
  if(mode.value === `edit`) init()
})
// #endregion

// #region Functions
async function init(){
  const result = await getDetail(props.record_id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    inputForm.value?.setValues(currentValue)
  }
}

function goBack() {
  router.go(-1)
}

async function handleConfirmAdd() {
  const inputData: any = await composeFormData()
  const response = mode.value === `add` 
  ? await handleActionSave(
      inputData,
      () => { },
      () => { },
      toast,
    )
  : await handleActionEdit(
      props.record_id,
      inputData,
      () => { },
      () => { },
      toast,
    )

  const data = (response?.body?.data ?? null)
  if (!data) return
  goBack()
}

async function composeFormData(): Promise<any> {
  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) return navigateTo(props.callbackUrl)
    goBack()
  }
}

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

// #region Watchers
// #endregion

const initial = {
  // subjective: '',
  // objective: '',
  // assesment: '',
  // planningGoal: '',
  // planningAction: '',
  // planningEducation: '',
  planningFrequency: 2,
  followUpPlan: 'EVALUASI', 
  // followUpPlanDesc: '',
}
</script>

<template>
  <div class="mb-5 border-b border-b-slate-300 pb-3 text-lg font-semibold xl:text-xl">
    Formulir Rawat Jalan KFR
  </div>
  <AppKfrEntry
    ref="inputForm"
    :schema="KfrSchema"
    :initial-values="initial"
  />
  
  <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>
