<script setup lang="ts">
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import { type Duration, intervalToDuration } from 'date-fns'

// schema
import { type ActionReportFormData, ActionReportSchema } from '~/schemas/action-report.schema'

// type
import type { Doctor } from '~/models/doctor'
import { type ClickType as ActionClickType } from '~/components/pub/my-ui/nav-footer/index'

// components
import * as DE from '~/components/pub/my-ui/doc-entry'
import Separator from '~/components/pub/ui/separator/Separator.vue'
import { ArrayMessage } from '~/components/pub/ui/form'
import ActionForm from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'

// form field components
import {
  FillNotes,
  RadioBloods,
  SelectBilling,
  SelectBirthPlace,
  SelectBirthType,
  SelectOperationSystem,
  SelectOperationType,
  SelectSpecimen,
  SelectSurgeryCounter,
  SelectSurgeryType,
} from './fields'
import { ButtonAction, Fragment, InputBase, TextAreaInput } from '~/components/pub/my-ui/form/'
import { SelectDoctor } from '~/components/app/doctor/fields'
// Helpers

// #region Props & Emits
interface FormData extends ActionReportFormData {
  _operationDuration: string
  _anesthesiaDuration: string
}

interface Props {
  isLoading: boolean
  mode: 'add' | 'edit' | 'view'
  initialValues?: Partial<FormData>

  // form related
  doctors: Doctor[]
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'submit', payload: FormData): void
  (e: 'back'): void
  (e: 'error', errors: Error): void
}>()

const tissueNotesLimit = 5
const mode = toRef(props, 'mode')
const isLoading = toRef(props, 'isLoading')

const isReadonly = computed(() => {
  if (isLoading.value === true) {
    return true
  }

  if (mode.value === 'view') {
    return true
  }

  return false
})

const formSchema = toTypedSchema(ActionReportSchema)

const { errors, handleSubmit, values, meta, resetForm, setFieldValue, setValues, validate } = useForm<FormData>({
  name: 'encounterActionReportForm',
  validationSchema: formSchema,
  initialValues: props.initialValues ? props.initialValues : {},
  validateOnMount: false,
})

defineExpose({
  validate,
  resetForm,
  setValues,
  values,
})
// #endregion

// #region State & Computed
// #endregion

// #region Lifecycle Hooks
// #endregion

// #region Functions
// #endregion region

// #region Utilities & event handlers
const onFormActionClicked = (action: ActionClickType) => {
  if (action === 'back') {
    emit('back')
    return
  }
  if (action === 'submit') {
    onSubmit()
    return
  }
}

const onSubmit = handleSubmit(
  (values) => {
    console.log(JSON.stringify(values))
    emit('submit', values)
  },
  (errors) => {
    console.error(errors)
    emit('error', new Error('Silahkan lengkapi form terlebih dahulu'))
  },
)
// #endregion

// #region Watcher
watch(
  () => [values.operationExecution.operationStartAt, values.operationExecution.operationEndAt],
  ([start, end]) => {
    if (!start || !end) return
    const pStart = new Date(start)
    const pEnd = new Date(end)

    const formatTime = (r: Duration) =>
      [r.hours && `${r.hours} jam`, r.minutes && `${r.minutes} menit`, r.seconds && `${r.seconds} detik`]
        .filter(Boolean)
        .join(' ')

    const res = intervalToDuration({
      start: pStart,
      end: pEnd,
    })

    setFieldValue('_operationDuration', formatTime(res))
  },
  { immediate: true },
)

watch(
  () => [values.operationExecution.anesthesiaStartAt, values.operationExecution.anesthesiaEndAt],
  ([start, end]) => {
    if (!start || !end) return
    const pStart = new Date(start)
    const pEnd = new Date(end)

    const formatTime = (r: Duration) =>
      [r.hours && `${r.hours} jam`, r.minutes && `${r.minutes} menit`, r.seconds && `${r.seconds} detik`]
        .filter(Boolean)
        .join(' ')

    const res = intervalToDuration({
      start: pStart,
      end: pEnd,
    })

    setFieldValue('_anesthesiaDuration', formatTime(res))
  },
  { immediate: true },
)
// #endregion
</script>

<template>
  <form @submit.prevent="onSubmit">
    <Fragment
      v-slot="{ section }"
      title="Tim Pelaksana Tindakan"
    >
      <p class="text-lg font-semibold">{{ section }}</p>

      <DE.Block
        :col-count="4"
        :cell-flex="false"
      >
        <SelectDoctor
          fieldName="operatorTeam.dpjpId"
          label="Dokter Pemeriksa"
          placeholder="Pilih dokter"
          :doctors="doctors"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operatorTeam.operatorName"
          label="Operator"
          placeholder="Masukkan operator"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operatorTeam.assistantOperatorName"
          label="Asisten Operator"
          placeholder="Masukkan asisten operator"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operatorTeam.instrumentNurseName"
          label="Instrumentir"
          placeholder="Masukkan instrumentir"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operatorTeam.surgeryDate"
          label="Tanggal Pembedahan"
          input-type="datetime-local"
          :is-disabled="isReadonly"
          placeholder=""
        />
      </DE.Block>
      <DE.Block
        :col-count="4"
        :cell-flex="false"
      >
        <TextAreaInput
          field-name="operatorTeam.actionDiagnosis"
          label="Diagnosa Tindakan"
          placeholder="Masukkan diagnosa tindakan"
          :col-span="2"
          :rows="5"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operatorTeam.postSurgeryNurseId"
          label="Perawat Pasca Bedah"
          placeholder="Masukkan perawat pasca bedah"
          :is-disabled="isReadonly"
        />
      </DE.Block>
    </Fragment>

    <Separator class="my-4" />

    <Fragment
      v-slot="{ section }"
      title="Tindakan Operatif/Non Operatif Lain"
    >
      <!-- <p class="text-lg font-semibold">{{ section }}</p> -->
      <DE.Block
        :col-count="2"
        :cell-flex="false"
      >
        <DE.Cell>
          <slot name="procedures" />
          <ArrayMessage
            class="mt-1"
            v-if="meta.touched"
            name="procedures"
          />
        </DE.Cell>
      </DE.Block>
    </Fragment>

    <Separator class="my-4" />

    <Fragment
      v-slot="{ section }"
      title="Data Pelaksanaan Operasi"
    >
      <p class="text-lg font-semibold">{{ section }}</p>

      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <SelectSurgeryType
          field-name="operationExecution.surgeryType"
          label="Jenis Operasi"
          placeholder="Pilih jenis operasi"
          :is-disabled="isReadonly"
        />
        <SelectBilling
          field-name="operationExecution.billingCode"
          label="Kode Billing"
          placeholder="Pilih kode billing"
          :is-disabled="isReadonly"
        />
        <SelectOperationSystem
          field-name="operationExecution.operationSystem"
          label="Sistem Operasi"
          placeholder="Pilih sistem operasi"
          :is-disabled="isReadonly"
        />
      </DE.Block>

      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <InputBase
          field-name="operationExecution.operationStartAt"
          label="Operasi Mulai"
          placeholder="Pilih Tanggal"
          input-type="datetime-local"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operationExecution.operationEndAt"
          label="Operasi Selesai"
          placeholder="Pilih Tanggal"
          input-type="datetime-local"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="_operationDuration"
          label="Lama Operasi"
          placeholder="-"
          is-disabled
        />
      </DE.Block>

      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <InputBase
          field-name="operationExecution.anesthesiaStartAt"
          label="Pembiusan Mulai"
          placeholder="Pilih Tanggal"
          input-type="datetime-local"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operationExecution.anesthesiaEndAt"
          label="Pembiusan Selesai"
          placeholder="Pilih Tanggal"
          input-type="datetime-local"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="_anesthesiaDuration"
          label="Lama Pembiusan"
          placeholder="-"
          is-disabled
        />
      </DE.Block>

      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <SelectOperationType
          field-name="operationExecution.surgeryCleanType"
          label="Jenis Pembedahan"
          placeholder="Pilih jenis pembedahan"
          :is-disabled="isReadonly"
        />
        <SelectSurgeryCounter
          field-name="operationExecution.surgeryNumber"
          label="Operasi Ke"
          placeholder="Pilih"
          :is-disabled="isReadonly"
        />
        <SelectBirthType
          field-name="operationExecution.birthRemark"
          label="Keterangan Lahir"
          placeholder="Pilih"
          :is-disabled="isReadonly"
        />
        <SelectBirthPlace
          field-name="operationExecution.birthPlaceNote"
          label="Ket. Tempat Lahir"
          placeholder="Pilih keterangan tempat lahir"
          :is-disabled="isReadonly"
        />

        <InputBase
          field-name="operationExecution.personWeight"
          label="Berat Badan"
          placeholder="Masukkan berat badan"
          numeric-only
          suffix-msg="Gram"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operationExecution.birthCondition"
          label="Ket. Saat Lahir"
          placeholder="Tambah catatan"
          :is-disabled="isReadonly"
        />
      </DE.Block>

      <DE.Block
        :col-count="4"
        :cell-flex="false"
      >
        <TextAreaInput
          field-name="operationExecution.operationDescription"
          label="Uraian Operasi"
          placeholder="Masukkan uraian"
          :rows="3"
          :col-span="2"
          :is-disabled="isReadonly"
        />
        <InputBase
          field-name="operationExecution.bleedingAmountCc"
          label="Jumlah Pendarahan"
          placeholder="Masukkan jumlah pendarahan"
          suffix-msg="CC"
          numeric-only
          :is-disabled="isReadonly"
        />
      </DE.Block>
      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <RadioBloods
          field-name="bloodInput"
          label="Jenis & Jumlah Darah Masuk"
          :is-disabled="isReadonly"
        />
      </DE.Block>

      <DE.Block
        :col-count="3"
        :cell-flex="false"
      >
        <InputBase
          field-name="implant.brand"
          label="Merk"
          placeholder="Masukkan merk"
          :is-disabled="isReadonly"
        />

        <InputBase
          field-name="implant.name"
          label="Nama Implant"
          placeholder="Masukkan nama implant"
          :is-disabled="isReadonly"
        />

        <InputBase
          field-name="implant.sticker"
          label="Sticker/Nomer Register Implant"
          placeholder="Masukkan sticker/nomor register implant"
          :is-disabled="isReadonly"
        />

        <InputBase
          field-name="implant.companionName"
          label="Nama Pendamping Implant"
          placeholder="Masukkan nama pendamping implant"
          :is-disabled="isReadonly"
        />
        <SelectSpecimen
          field-name="specimen.destination"
          label="Specimen/Jaringan dikirim ke"
          placeholder="Pilih"
          :is-disabled="isReadonly"
        />
      </DE.Block>
      <FillNotes
        title="Keterangan Jaringan"
        :limit="tissueNotesLimit"
        :is-disabled="isReadonly"
      />
    </Fragment>
    <div class="mt-4 flex justify-end">
      <ActionForm @click="onFormActionClicked" />
    </div>
  </form>
</template>
