<script setup lang="ts">
import type { ExposedForm } from '~/types/form';
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
import { getDetail } from '~/services/therapy-protocol.service';
import { handleActionEdit } from '~/handlers/therapy-protocol.handler'
import { TherapyProtocolMedicRehabilitationSchema } from '~/schemas/therapy-protocol.schema';

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

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

// #region State & Computed
const router = useRouter()
const route = useRoute()
const encounterId = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0
const therapyId = typeof route.params.therapy_protocol_id == 'string' ? parseInt(route.params.therapy_protocol_id) : 0
const isConfirmationOpen = ref(false)
// #endregion

// #region Lifecycle Hooks
onMounted(async () => {
  const result = await getDetail(therapyId)
  if (result.success) {
    const currentValue = result.body?.data || {}
    currentValue.medicalDiagnoses = await JSON.parse(currentValue.medicalDiagnoses)
    currentValue.functionDiagnoses = await JSON.parse(currentValue.functionDiagnoses)
    currentValue.procedures = await JSON.parse(currentValue.procedures)
    console.log(currentValue)
    inputForm.value?.setValues(currentValue)
  }
})
// #endregion

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

async function handleConfirmAdd() {
  const inputData: any = await composeFormData()
  const response = await handleActionEdit(
    inputData,
    therapyId,
    () => { },
    () => { },
    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.medicalDiagnoses = JSON.stringify(formData.medicalDiagnoses)
  formData.functionDiagnoses = JSON.stringify(formData.functionDiagnoses)
  formData.procedures = JSON.stringify(formData.procedures)
  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) return navigateTo(props.callbackUrl)
    goBack()
  }
}

function handleCancelAdd() {
  isConfirmationOpen.value = false
}
// #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">Edit</div>
  <AppTherapyProtocolEntry
    ref="inputForm"
    :schema="TherapyProtocolMedicRehabilitationSchema"
    :resume-arrangement-type="inputForm?.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"
  />
</template>
