<script setup lang="ts">
import type { FormErrors } from '~/types/error'
import { toTypedSchema } from '@vee-validate/zod'
import { Form } from '~/components/pub/ui/form'
import { FieldArray } from 'vee-validate'
import SelectDate from './_common/select-date.vue'
import InputBase from '~/components/pub/my-ui/form/input-base.vue'

import * as DE from '~/components/pub/my-ui/doc-entry'
import TextAreaInput from '~/components/pub/my-ui/form/text-area-input.vue'
import SelectArrangement from './_common/select-arrangement.vue'
import type { ResumeArrangementType } from '~/schemas/resume.schema'
import SelectFaskes from './_common/select-faskes.vue'
import SelectDeathCause from './_common/select-death-cause.vue'
import SelectIcd10 from './_common/select-icd-10.vue'
import SelectIcd9 from './_common/select-icd-9.vue'
import SelectConciousLevel from './_common/select-concious-level.vue'
import SelectPainScale from './_common/select-pain-scale.vue'
import SelectNationalProgramService from './_common/select-national-program-service.vue'
import SelectNationalProgramServiceStatus from './_common/select-national-program-service-status.vue'
import SelectHospitalLeaveCondition from './_common/select-hospital-leave-condition.vue'
import SelectHospitalLeaveMethod from './_common/select-hospital-leave-method.vue'

const props = defineProps<{
  schema: any
  initialValues?: any
  resumeArrangementType: ResumeArrangementType
  errors?: FormErrors
}>()

const isActionHistoryOpen = inject(`isActionHistoryOpen`) as Ref<boolean>
const isConsultationHistoryOpen = inject(`isConsultationHistoryOpen`) as Ref<boolean>
const isSupportingHistoryOpen = inject(`isSupportingHistoryOpen`) as Ref<boolean>
const isFarmacyHistoryOpen = inject(`isFarmacyHistoryOpen`) as Ref<boolean>
const isNationalProgramServiceHistoryOpen = inject(`isNationalProgramServiceHistoryOpen`) as Ref<boolean>
const formSchema = toTypedSchema(props.schema)
const formRef = ref()

defineExpose({
  validate: () => formRef.value?.validate(),
  resetForm: () => formRef.value?.resetForm(),
  setValues: (values: any, shouldValidate = true) => formRef.value?.setValues(values, shouldValidate),
  values: computed(() => formRef.value?.values),
})

const DEFAULT_SECONDARY_DIAGNOSIS_VALUE = {
  diagnosis: '',
  icd10: '',
  diagnosisBasis: '',
};
const DEFAULT_SECONDARY_ACTION_VALUE = {
  action: '',
  icd9: '',
  actionBasis: '',
};
const DEFAULT_CONSULTATION_VALUE = {
  consultation: '',
  consultationReply: '',
};

const initialFormValues = {
  secondaryDiagnosis: [DEFAULT_SECONDARY_DIAGNOSIS_VALUE],
  secondaryOperativeNonOperativeAct: [DEFAULT_SECONDARY_ACTION_VALUE],
  consultation: [DEFAULT_CONSULTATION_VALUE],
}
</script>

<template>
  <Form ref="formRef"
    v-slot="{ values }"
    as=""
    keep-values
    :validation-schema="formSchema"
    :validate-on-mount="false"
    validation-mode="onSubmit"
    :initial-values="initialValues ? initialValues : initialFormValues">

    <!-- Pasien -->
    <h1 class="mb-3 text-base font-medium">Pemeriksaan Pasien</h1>
    <DE.Block :col-count="3" :cell-flex="false">
      <SelectDate field-name="inDate" label="Tanggal Masuk" :errors="errors" :is-disabled="true" />
      <SelectDate field-name="outDate" label="Tanggal Keluar" :errors="errors" :is-disabled="true" />      
      <InputBase
        field-name="doctor_id"
        :is-disabled="true"
        label="DPJP" placeholder="DPJP"/>
    </DE.Block> 
    <DE.Block class="" :cell-flex="false">   
      <InputBase
        class="w-2/3"
        field-name="first_diagnosis"
        :is-disabled="true"
        label="Diagnosis Masuk/Rujukan" placeholder="Diagnosis Masuk/Rujukan"/>
    </DE.Block> 
    <DE.Block :col-count="3" :cell-flex="false">
      <TextAreaInput field-name="supplementCheckup"
        label="Indikasi Rawat Jalan" placeholder="Indikasi Rawat Jalan" :errors="errors" />
      <TextAreaInput field-name="supplementCheckup"
        label="Keluhan Utama (Singkat & Menunjang)" placeholder="Keluhan Utama (Singkat & Menunjang)" :errors="errors" />
      <TextAreaInput field-name="supplementCheckup"
        label="Pemeriksaan Fisik (Singkat & Menunjang)" placeholder="Pemeriksaan Fisik (Singkat & Menunjang)" :errors="errors" />
      <TextAreaInput field-name="supplementCheckup"
        label="Riwayat Penyakit" placeholder="Riwayat Penyakit" :errors="errors" />
      <TextAreaInput field-name="supplementCheckup"
        label="Diagnosa Medis" placeholder="Diagnosa Medis" :errors="errors" />
    </DE.Block>
    <Separator class="my-4" />



    <!-- DIAGNOSIS -->
    <h1 class="mb-3 text-base font-medium">Diagnosa</h1>
    <h1 class="mb-3 text-base font-medium">Diagnosa Utama</h1>
    <DE.Block :col-count="2" class="" :cell-flex="false">   
      <InputBase
        field-name="diagnosis"
        label="Diagnosa" placeholder="Masukkan Diagnosa"
        :errors="errors" is-required />
      <SelectIcd10
        field-name="primaryDiagnosis"
        label="ICD 10"
        placeholder="ICD 10"
        :errors="errors" is-required />
      <DE.Cell :col-span="2">
        <TextAreaInput field-name="supplementCheckup"
        label="Dasar Diagnosa" placeholder="Masukkan Dasar Diagnosa utama Pasien" :errors="errors" />
      </DE.Cell>


      <DE.Cell :col-span="2">
        <h1 class="mb-3 text-base font-medium">Diagnosa Sekunder</h1>
        <div class="w-full rounded-md border bg-gray-50/50 p-4 shadow-sm dark:bg-neutral-950">

          <FieldArray v-slot="{ fields, push, remove }" name="secondaryDiagnosis">
            <div v-for="(field, idx) in fields" :key="idx" class="flex items-center gap-3 mb-3">
              <div class="w-full">
                <h1 class="font-medium">Diagnosa {{ idx + 1 }}</h1>
                <div class="flex gap-3">
                  <InputBase
                    :field-name="`secondaryDiagnosis[${idx}].diagnosis`"
                    label="Diagnosa" placeholder="Masukkan Diagnosa"
                    :errors="errors" is-required />
                  <SelectIcd10
                    :field-name="`secondaryDiagnosis[${idx}].icd10`"
                    label="ICD 10"
                    placeholder="ICD 10"
                    :errors="errors" is-required />
                </div>
                <TextAreaInput :field-name="`secondaryDiagnosis[${idx}].diagnosisBasis`"
                  label="Dasar Diagnosa" placeholder="Masukkan Dasar Diagnosa Pasien" :errors="errors" />
              </div>
              <Button v-if="idx !== 0" type="button" variant="destructive" size="sm" @click="remove(idx)">
                <Icon name="i-lucide-trash-2" class="h-4 w-4" />
              </Button>
            </div>
            <Button type="button" variant="outline"
              class="w-full rounded-md border border-primary bg-white px-4 py-2 text-primary hover:border-primary hover:bg-primary hover:text-white sm:w-auto sm:text-sm"
              @click="push(DEFAULT_SECONDARY_DIAGNOSIS_VALUE)">
              <Icon name="i-lucide-plus" class="mr-2 h-4 w-4 align-middle transition-colors" />
              Tambah Diagnosis
            </Button>
          </FieldArray>
        </div>
      </DE.Cell>


      
    </DE.Block>
    <Separator class="my-4" />




    <!-- Tindakan OPERATIF/NON OPERATIF -->
    <div class="mb-3 flex gap-3 items-center">
      <h1 class="text-base font-medium">Tindakan Operatif/Non Operatif</h1>
      <Button variant="ghost"
        class="gap-1 items-center text-orange-400"
        @click="isActionHistoryOpen = true">
        <Icon name="i-lucide-history" class="h-4 w-4" /> Riwayat Tindakan</Button>
    </div>
    <h1 class="mb-3 font-normal">Tindakan Operatif/Non Operatif Utama</h1>
    <DE.Block :col-count="2" class="" :cell-flex="false">   
      <InputBase
        field-name="diagnosis"
        label="Tindakan" placeholder="Masukkan Tindakan"
        :errors="errors" is-required />
      <SelectIcd9
        field-name="primaryDiagnosis"
        label="ICD 9"
        placeholder="ICD 9"
        :errors="errors" is-required />
      <DE.Cell :col-span="2">        
        <TextAreaInput field-name="supplementCheckup"
          label="Dasar Tindakan" placeholder="Masukkan Dasar Tindakan utama Pasien" :errors="errors" />
      </DE.Cell>

      <DE.Cell :col-span="2">
        <h1 class="mb-3 text-base font-medium">Tindakan Lain</h1>
        <div class="w-full rounded-md border bg-gray-50/50 p-4 shadow-sm dark:bg-neutral-950">

          <FieldArray v-slot="{ fields, push, remove }" name="secondaryOperativeNonOperativeAct">
            <div v-for="(field, idx) in fields" :key="idx" class="flex items-center gap-3 mb-3">
              <div class="w-full">
                <h1 class="font-medium">Tindakan {{ idx + 1 }}</h1>
                <div class="flex gap-3">
                  <InputBase
                    :field-name="`secondaryOperativeNonOperativeAct[${idx}].action`"
                    label="Tindakan" placeholder="Masukkan Tindakan"
                    :errors="errors" is-required />
                  <SelectIcd10
                    :field-name="`secondaryOperativeNonOperativeAct[${idx}].icd9`"
                    label="ICD 10"
                    placeholder="ICD 10"
                    :errors="errors" is-required />
                </div>
                <TextAreaInput :field-name="`secondaryOperativeNonOperativeAct[${idx}].actionBasis`"
                  label="Dasar Tindakan" placeholder="Masukkan Dasar Tindakan Pasien" :errors="errors" />
              </div>
              <Button v-if="idx !== 0" type="button" variant="destructive" size="sm" @click="remove(idx)">
                <Icon name="i-lucide-trash-2" class="h-4 w-4" />
              </Button>
            </div>
            <Button type="button" variant="outline"
              class="w-full rounded-md border border-primary bg-white px-4 py-2 text-primary hover:border-primary hover:bg-primary hover:text-white sm:w-auto sm:text-sm"
              @click="push(DEFAULT_SECONDARY_ACTION_VALUE)">
              <Icon name="i-lucide-plus" class="mr-2 h-4 w-4 align-middle transition-colors" />
              Tambah Tindakan
            </Button>
          </FieldArray>
        </div>
      </DE.Cell>
      
    </DE.Block>    
    <TextAreaInput :field-name="`medicalAction`"
      label="Tindakan Medis" placeholder="Masukkan Tindakan Medis" :errors="errors" />
    <Separator class="my-4" />



    <!-- KONSULTASI -->
    <div class="mb-3 flex gap-3 items-center">
      <h1 class="text-base font-medium">Konsultasi</h1>
      <Button variant="ghost"
        class="gap-1 items-center text-orange-400"
        @click="isConsultationHistoryOpen = true">
        <Icon name="i-lucide-history" class="h-4 w-4" /> Riwayat Konsultasi</Button>
    </div>
      <div class="w-full rounded-md border bg-gray-50/50 p-4 shadow-sm dark:bg-neutral-950">
        <FieldArray v-slot="{ fields, push, remove }" name="consultation">
          <div v-for="(field, idx) in fields" :key="idx" class="flex items-center gap-3 mb-3">
            <div class="w-full">
              <h1 class="font-medium mb-1">Konsultasi {{ idx + 1 }}</h1>
              <div class="flex gap-3">
                <TextAreaInput :field-name="`consultation[${idx}].consultation`"
                  label="Konsultasi" placeholder="Masukkan Konsultasi" :errors="errors" />
                <TextAreaInput :field-name="`consultation[${idx}].consultationReply`"
                  label="Jawaban Konsultasi" placeholder="Masukkan Jawaban Konsultasi" :errors="errors" />
              </div>
            </div>
            <Button v-if="idx !== 0" type="button" variant="destructive" size="sm" @click="remove(idx)">
              <Icon name="i-lucide-trash-2" class="h-4 w-4" />
            </Button>
          </div>
          <Button type="button" variant="outline"
            class="w-full rounded-md border border-primary bg-white px-4 py-2 text-primary hover:border-primary hover:bg-primary hover:text-white sm:w-auto sm:text-sm"
            @click="push(DEFAULT_CONSULTATION_VALUE)">
            <Icon name="i-lucide-plus" class="mr-2 h-4 w-4 align-middle transition-colors" />
            Tambah Konsultasi
          </Button>
        </FieldArray>
      </div>
    <Separator class="my-4" />



    <!-- DATA PENUNJANG -->
    <section>
      <div class="mb-3 flex gap-3 items-center">
        <h1 class="text-base font-medium">Data Penunjang</h1>
        <Button variant="ghost"
          class="gap-1 items-center text-orange-400"
          @click="isSupportingHistoryOpen = true">
          <Icon name="i-lucide-history" class="h-4 w-4" /> Riwayat Data Penunjang</Button>
      </div>
      <DE.Block class="" :cell-flex="false">
        <TextAreaInput field-name="supplementCheckup" label="Pemeriksaan Penunjang" placeholder="Masukkan Pemeriksaan Penunjang" :errors="errors" />
      </DE.Block>
    </section>
    <Separator class="my-4" />



    <!-- DATA Farmasi -->
    <section>
      <div class="mb-3 flex gap-3 items-center">
        <h1 class="text-base font-medium">Data Farmasi</h1>
        <Button variant="ghost"
          class="gap-1 items-center text-orange-400"
          @click="isFarmacyHistoryOpen = true">
          <Icon name="i-lucide-history" class="h-4 w-4" /> Riwayat Data Farmasi</Button>
      </div>
      <DE.Block class="items-end" :col-count="2" :cell-flex="false">
        <TextAreaInput field-name="supplementCheckup"
          label="Kelainan Khusus Alergi" placeholder="Masukkan Kelainan Khusus Alergi" :errors="errors" />
        <TextAreaInput field-name="supplementCheckup"
          label="Kelainan Lain" placeholder="Masukkan Kelainan Lain" :errors="errors" />
        <TextAreaInput field-name="supplementCheckup"
          label="Terapi yang Diberikan (Farmakologi dan Non Farmakologi) Selama Dirawat" placeholder="Masukkan Terapi yang Diberikan (Farmakologi dan Non Farmakologi) Selama Dirawat" :errors="errors" />
        <TextAreaInput field-name="supplementCheckup"
          label="Terapi yang Diberikan (Farmakologi dan Non Farmakologi) Waktu Pulang" placeholder="Masukkan Terapi yang Diberikan (Farmakologi dan Non Farmakologi) Waktu Pulang" :errors="errors" />
        <TextAreaInput field-name="supplementCheckup"
          label="Instruksi Tindak Lanjut/Anjuran dan Edukasi (Follow Up/Kontrol)" placeholder="Masukkan Instruksi Tindak Lanjut/Anjuran dan Edukasi (Follow Up/Kontrol)" :errors="errors" />
      </DE.Block>
    </section>
    <Separator class="my-4" />



    <!-- Keadaan Waktu Keluar -->
    <section>
      <h1 class="mb-3 font-medium">Keadaan Waktu Keluar</h1>
      <DE.Block :col-count="4" :cell-flex="false">
        <InputBase
          :field-name="`aaaaaaaaaaa`"
          label="Tekanan Darah Sistol" placeholder="Masukkan Tekanan Darah Sistol"
          right-label="mmHg" bottom-label="Contoh: 90"
          :errors="errors" is-required numeric-only />
        <InputBase
          :field-name="`aaaaaaaaaaa`"
          label="Tekanan Darah Diastol" placeholder="Masukkan Tekanan Darah Diastol"
          right-label="mmHg" bottom-label="Contoh: 60"
          :errors="errors" is-required numeric-only />
        <InputBase
          :field-name="`aaaaaaaaaaa`"
          label="Pernafasan" placeholder="Masukkan Pernafasan"
          right-label="kali / menit" bottom-label="Contoh: 20"
          :errors="errors" is-required numeric-only />
        <InputBase
          :field-name="`aaaaaaaaaaa`"
          label="Denyut Jantung" placeholder="Masukkan Denyut Jantung"
          right-label="kali / menit" bottom-label="Contoh: 20"
          :errors="errors" is-required numeric-only />
        <InputBase
          :field-name="`aaaaaaaaaaa`"
          label="Suhu Tubuh" placeholder="Masukkan Suhu Tubuh"
          right-label="'C" bottom-label="Contoh: 37"
          :errors="errors" is-required numeric-only />
        <SelectConciousLevel
          :field-name="`aaaaaaaaaaa`"
          label="Tingkat Kesadaran"
          placeholder="Tingkat Kesadaran"
          :errors="errors" is-required />
        <SelectPainScale
          :field-name="`aaaaaaaaaaa`"
          label="Skala Nyeri"
          placeholder="Skala Nyeri"
          :errors="errors" is-required />
      </DE.Block>
    </section>
    <Separator class="my-4" />



    <!-- Program Nasional -->
    <section>
      <div class="mb-3 flex gap-3 items-center">
        <h1 class="text-base font-medium">Program Nasional</h1>
        <Button variant="ghost"
          class="gap-1 items-center text-orange-400"
          @click="isNationalProgramServiceHistoryOpen = true">
          <Icon name="i-lucide-history" class="h-4 w-4" /> Riwayat Program Nasional</Button>
      </div>
      <DE.Block :col-count="3" :cell-flex="false">
        <SelectNationalProgramService
          :field-name="`aaaaaaaaaaa`"
          label="Layanan Program Nasional"
          placeholder="Layanan Program Nasional"
          :errors="errors" is-required />
        <SelectNationalProgramServiceStatus
          :field-name="`aaaaaaaaaaa`"
          label="Status Layanan Program Nasional"
          placeholder="Status Layanan Program Nasional"
          :errors="errors" is-required />
      </DE.Block>
    </section>
    <Separator class="my-4" />  



    <!-- Penatalaksanaan -->
    <section>
      <h1 class="mb-3 font-medium">Penatalaksanaan</h1>
      <DE.Block :col-count="3" :cell-flex="false">
        <SelectArrangement
          field-name="arrangement"
          label="Lanjutan Penatalaksanaan"
          placeholder="Pilih Arrangement"
          :errors="errors" />
        <SelectHospitalLeaveCondition
          :field-name="`aaaaaaaaaaa`"
          label="Kondisi Meninggalkan RS"
          placeholder="Kondisi Meninggalkan RS"
          :errors="errors" is-required />
        <SelectHospitalLeaveMethod
          :field-name="`aaaaaaaaaaa`"
          label="Cara Keluar RS"
          placeholder="Cara Keluar RS"
          :errors="errors" is-required />
      </DE.Block>
    </section>

    <DE.Cell :col-span="3"
      v-show="resumeArrangementType === `mrs`">
      <TextAreaInput
        field-name="inpatientIndication"
        label="Indikasi Rawat Jalan"
        placeholder="Indikasi Rawat Jalan"
        :errors="errors" />
    </DE.Cell>

    <DE.Block :col-count="3" :cell-flex="false">      
      <SelectFaskes
        v-show="resumeArrangementType === `rujukExternal` "
        field-name="faskes"
        label="Faskes"
        placeholder="Pilih Faskes"
        :errors="errors"
      />
      <InputBase
        v-show="resumeArrangementType === `rujukExternal` "
        field-name="clinic"
        label="Klinik"
        placeholder="Masukkan Klinik"
        :errors="errors"
      />

      <SelectDate
        v-show="resumeArrangementType === `meninggal`"
        field-name="deathDate"
        label="Jam Tanggal Meninggal"
        :errors="errors"
        :is-with-time="true" />
      
      <DE.Cell class="mt-2" :col-span="3" v-show="resumeArrangementType === `meninggal`">
        <div class="w-2/3 rounded-md border bg-gray-50/50 p-4 shadow-sm dark:bg-neutral-950">
          <h1 class="mb-3 font-medium">Sebab Meninggal</h1>

          <FieldArray v-slot="{ fields, push, remove }" name="deathCause">
            <div v-for="(field, idx) in fields" :key="idx" class="flex items-center gap-3 mb-3">
              <SelectDeathCause
                :field-name="`deathCause[${idx}]`"
                :errors="errors"
              />
              <Button v-if="idx !== 0" type="button" variant="destructive" size="sm" @click="remove(idx)">
                <Icon name="i-lucide-trash-2" class="h-4 w-4" />
              </Button>
            </div>
            <Button v-if="fields.length < 3" type="button" variant="outline"
              class="w-full rounded-md border border-primary bg-white px-4 py-2 text-primary hover:border-primary hover:bg-primary hover:text-white sm:w-auto sm:text-sm"
              @click="push(``)">
              <Icon name="i-lucide-plus" class="mr-2 h-4 w-4 align-middle transition-colors" />
              Tambah Sebab Meninggal
            </Button>
          </FieldArray>
        </div>
      </DE.Cell>

      <DE.Cell 
        v-show="resumeArrangementType === `meninggal`"
        :col-span="3">
        <TextAreaInput            
            field-name="deathCauseDescription"
            label="Keterangan Sebab Meninggal"
            placeholder="Keterangan Sebab Meninggal"
            :errors="errors" />
      </DE.Cell>
    
    </DE.Block>

  </Form>
</template>
