<script setup lang="ts">
import { z } from 'zod'
import Entry from '~/components/app/general-consent/entry.vue'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su-pr.vue'
import ActionDialog from '~/components/pub/my-ui/nav-footer/ba-su.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import { GeneralConsentSchema } from '~/schemas/general-consent.schema'
import { toast } from '~/components/pub/ui/toast'
import { handleActionSave, handleActionEdit } from '~/handlers/general-consent.handler'
import { create } from '~/services/generate-file.service'
// Services
import { getDetail } from '~/services/general-consent.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 = GeneralConsentSchema
const payload = ref({
  encounter_id: 0,
  value: '',
})
const model = ref({
  relatives: [],
  responsibleName: '',
  responsiblePhone: '',
  informant: '',
  witness1: '',
  witness2: '',
})

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) {
    loadEntryForEdit(+recordId)
  }
})

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

  if (result?.success) {
    const data = result.body?.data || {}

    const value = JSON.parse(data.value || '{}')
    model.value.witness1 = value?.witness1 || ''
    model.value.witness2 = value?.witness2 || ''
    model.value.informant = value?.informant || ''
    model.value.responsibleName = value?.responsible || ''
    model.value.responsiblePhone = value?.responsiblePhone || ''
    model.value.relatives = value?.relatives || []
    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') {
    const data = await getDetail(recordId.value)
    const detail = data.body?.data
    fileUrl.value = detail?.fileUrl
    isOpenDiagnose.value = true
    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,
      },
      () => {},
      () => {},
      toast,
    )
    const data = resp.body?.data
    if (data) {
      const resp2 = await create({
        entityType_code: 'encounter',
        ref_id: data?.id,
        type_code: 'general-consent',
      })
      console.log('resp2', resp2.body?.data)
      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>
