<script setup lang="ts">
import { z } from 'zod'
import Entry from '~/components/app/summary-medic/entry.vue'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import ActionDialog from '~/components/pub/my-ui/nav-footer/ba-su.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import { SummaryMedicSchema } from '~/schemas/soapi.schema'
import { toast } from '~/components/pub/ui/toast'
import { handleActionSave, handleActionEdit } from '~/handlers/soapi-early.handler'
// Services
import { getDetail } from '~/services/summary-medic.service'
const { backToList } = useQueryCRUDMode('mode')
const { recordId } = useQueryCRUDRecordId('record-id')

const route = useRoute()
const isOpenProcedure = ref(false)
const isOpenDiagnose = ref(false)
const isOpenFungsional = ref(false)
const procedures = ref([])
const diagnoses = ref([])
const fungsional = ref([])
const selectedProcedure = ref<any>(null)
const selectedDiagnose = ref<any>(null)
const selectedFungsional = ref<any>(null)
const schema = SummaryMedicSchema
const payload = ref({
  typeCode: 'amb-resume',
  encounter_id: 0,
  time: '',
  value: '',
})
const model = ref({
  date: '',
  doctor: '',
  diagnosis: '',
  essay: '',
  plan: '',
  note: '',
})

const fileUrl = ref('')
const isLoading = reactive<DataTableLoader>({
  isTableLoading: false,
})

async function getDiagnoses() {
  isLoading.isTableLoading = true
  const resp = await xfetch('/api/v1/diagnose-src')
  if (resp.success) {
    diagnoses.value = (resp.body as Record<string, any>).data
  }
  isLoading.isTableLoading = false
}

async function getProcedures() {
  isLoading.isTableLoading = true
  const resp = await xfetch('/api/v1/procedure-src')
  if (resp.success) {
    procedures.value = (resp.body as Record<string, any>).data
  }
  isLoading.isTableLoading = false
}

onMounted(() => {
  const mode = route.query.mode
  const recordId = route.query['record-id']
  if (mode === 'entry' && recordId) {
  }
})

// TODO: mapping data detail when edit
const loadEntryForEdit = async (id: number) => {
  const result = await getDetail(id)

  if (result?.success) {
    console.log('model', model.value)
  }
}

function handleClick(type: string) {
  if (type === 'prosedur') {
    isOpenProcedure.value = true
  } else if (type === 'diagnosa') {
    isOpenDiagnose.value = true
  } else if (type === 'fungsional') {
    isOpenDiagnose.value = true
  }
}
const entryGeneralConsent = ref()
async function actionHandler(type: string) {
  if (type === 'back') {
    backToList()
    return
  }
  if (type === 'print') {
    return
  }
  const result = await entryGeneralConsent.value?.validate()
  if (result?.valid) {
    // if (result.data.relatives.length > 0) {
    //   result.data.relatives = result.data.relatives.map((item: any) => {
    //     return item.name
    //   })
    // }

    console.log('data', result)
    const resp = await handleActionSave(
      {
        ...payload.value,
        value: JSON.stringify(result.data),
        encounter_id: +route.params.id,
        time: new Date().toISOString(),
      },
      () => {},
      () => {},
      toast,
    )
    backToList()
  } else {
    console.log('Ada error di form', result)
  }
}

const icdPreview = ref({
  procedures: [],
  diagnoses: [],
})

function actionDialogHandler(type: string) {
  if (type === 'submit') {
    // icdPreview.value.procedures = selectedProcedure.value || []
    // icdPreview.value.diagnoses = selectedDiagnose.value || []
    // icdPreview.value.fungsional = selectedFungsional.value || []
  }
  isOpenProcedure.value = false
  isOpenDiagnose.value = false
}

provide('table_data_loader', isLoading)
provide('icdPreview', icdPreview)
</script>
<template>
  <Entry
    ref="entryGeneralConsent"
    v-model="model"
    :schema="schema"
    @click="handleClick"
  />
  <div class="my-2 flex justify-end py-2">
    <Action @click="actionHandler" />
  </div>
  <Dialog
    v-model:open="isOpenDiagnose"
    title="Preview General Content"
    size="xl"
    prevent-outside
  >
    <embed
      style="width: 100%; height: 90vh"
      :src="fileUrl"
    />
  </Dialog>
</template>
