<script setup lang="ts">
import { computed, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// Components
import EncounterPatientInfo from '~/components/app/encounter/collapsible-patient-info.vue'
import EncounterHistoryButtonMenu from '~/components/app/encounter/history-button-menu.vue'
import SubMenu from '~/components/pub/my-ui/menus/submenu.vue'

// Libraries
import { getPositionAs } from '~/lib/roles'

// Types
import type { EncounterProps } from '~/handlers/encounter-process.handler'

// Services
import { getDetail } from '~/services/encounter.service'

// Handlers
import { getIndexById, listItems, mapResponseToEncounter } from '~/handlers/encounter-process.handler'

const StatusAsync = defineAsyncComponent(() => import('~/components/content/encounter/status.vue'))
const AssesmentFunctionListAsync = defineAsyncComponent(() => import('~/components/content/soapi/entry.vue'))
const EarlyMedicalAssesmentListAsync = defineAsyncComponent(() => import('~/components/content/soapi/entry.vue'))
const EarlyMedicalRehabListAsync = defineAsyncComponent(() => import('~/components/content/soapi/entry.vue'))
const PrescriptionAsync = defineAsyncComponent(() => import('~/components/content/prescription/main.vue'))
// const PrescriptionListAsync = defineAsyncComponent(() => import('~/components/content/prescription/list.vue'))
const CpLabOrderAsync = defineAsyncComponent(() => import('~/components/content/cp-lab-order/main.vue'))
const RadiologyAsync = defineAsyncComponent(() => import('~/components/content/radiology-order/main.vue'))
const ConsultationAsync = defineAsyncComponent(() => import('~/components/content/consultation/list.vue'))
const ControlLetterListAsync = defineAsyncComponent(() => import('~/components/content/control-letter/list.vue'))
const ProtocolListAsync = defineAsyncComponent(() => import('~/components/app/chemotherapy/list.protocol.vue'))
const MedicineProtocolListAsync = defineAsyncComponent(() => import('~/components/app/chemotherapy/list.medicine.vue'))

const { user, getActiveRole } = useUserStore()
const route = useRoute()
const router = useRouter()

const props = defineProps<{
  classCode?: EncounterProps['classCode']
  subClassCode?: EncounterProps['subClassCode']
}>()

const activeRole = getActiveRole()
const activePosition = ref(getPositionAs(activeRole))
const menus = ref([] as any)
const activeMenu = computed({
  get: () => (route.query?.menu && typeof route.query.menu === 'string' ? route.query.menu : 'status'),
  set: (value: string) => {
    router.replace({ path: route.path, query: { menu: value } })
  },
})

const id = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0
const data = ref<any>(null)
const isShowPatient = computed(() => data.value && data.value?.patient?.person)

if (activePosition.value === 'none') { // if user position is none, redirect to home page
  router.push('/')
}

// Dummy rows for ProtocolList (matches keys expected by list-cfg.protocol)
const protocolRows = [
  {
    number: '1',
    tanggal: new Date().toISOString().substring(0, 10),
    siklus: 'I',
    periode: 'Siklus I',
    kehadiran: 'Hadir',
    action: '',
  },
  {
    number: '2',
    tanggal: new Date().toISOString().substring(0, 10),
    siklus: 'II',
    periode: 'Siklus II',
    kehadiran: 'Tidak Hadir',
    action: '',
  },
]

const paginationMeta = {
  recordCount: protocolRows.length,
  page: 1,
  pageSize: 10,
  totalPage: 1,
  hasNext: false,
  hasPrev: false,
}

async function getData() {
  try {
    const dataRes = await getDetail(id, {
      includes:
        'patient,patient-person,patient-person-addresses,unit,Appointment_Doctor,Appointment_Doctor-employee,Appointment_Doctor-employee-person,Responsible_Doctor,Responsible_Doctor-employee,Responsible_Doctor-employee-person',
    })
    const dataResBody = dataRes.body ?? null
    const result = dataResBody?.data ?? null

    if (result) {
      const mappedData = mapResponseToEncounter(result)
      if (mappedData) {
        data.value = mappedData
      } else {
        data.value = null
      }
    } else {
      data.value = null
    }
  } catch (error) {
    console.error('Error fetching encounter data:', error)
    data.value = null
  }
}

function getMenus() {
  const normalClassCode = props.classCode === 'ambulatory' ? 'outpatient' : props.classCode
  const currentListItems = listItems[`installation|${normalClassCode}`];
  if (!currentListItems) return []
  const unitCode = user?.unit?.code ? `unit|${user.unit.code}` : 'all';
  const currentUnitItems: any = currentListItems[`${unitCode}`];
  if (!currentUnitItems) return []
  let menus = []
  if (currentUnitItems.roles && currentUnitItems.roles?.some((role: string) => role === activePosition.value)) {
    menus = [...currentUnitItems.items]
  } else {
    menus = [...currentUnitItems]
  }
  const indexStatus = getIndexById('status', menus)
  const indexEarlyMedicalAssessment = getIndexById('early-medical-assessment', menus)
  const indexRehabMedicalAssessment = getIndexById('rehab-medical-assessment', menus)
  const indexFunctionAssessment = getIndexById('function-assessment', menus)
  const indexTherapyProtocol = getIndexById('therapy-protocol', menus)
  const indexChemotherapyProtocol = getIndexById('chemotherapy-protocol', menus)
  const indexChemotherapyMedicine = getIndexById('chemotherapy-medicine', menus)
  const indexPrescription = getIndexById('prescription', menus)
  const indexDevice = getIndexById('device', menus)
  const indexMcuRadiology = getIndexById('mcu-radiology', menus)
  const indexMcuLabPc = getIndexById('mcu-lab-pc', menus)
  const indexMcuLabMicro = getIndexById('mcu-lab-micro', menus)
  const indexMcuLabPa = getIndexById('mcu-lab-pa', menus)
  const indexMedicalAction = getIndexById('medical-action', menus)
  const indexMcuResult = getIndexById('mcu-result', menus)
  const indexConsultation = getIndexById('consultation', menus)
  const indexResume = getIndexById('resume', menus)
  const indexControlLetter = getIndexById('control', menus)
  const indexScreening = getIndexById('screening', menus)
  const indexSupportingDocument = getIndexById('supporting-document', menus)
  const indexPriceList = getIndexById('price-list', menus)

  if (indexStatus > -1) {
    menus.splice(indexStatus, 1, {
      ...menus[indexStatus],
      component: StatusAsync,
      props: { encounter: data },
    })
  }
  if (indexEarlyMedicalAssessment > -1) {
    menus.splice(indexEarlyMedicalAssessment, 1, {
      ...menus[indexEarlyMedicalAssessment],
      component: EarlyMedicalAssesmentListAsync,
      props: { encounter: data, type: 'early-medic', label: 'Pengkajian Awal Medis' },
    })
  }
  if (indexRehabMedicalAssessment > -1) {
    menus.splice(indexRehabMedicalAssessment, 1, {
      ...menus[indexRehabMedicalAssessment],
      component: EarlyMedicalRehabListAsync,
      props: { encounter: data, type: 'early-rehab', label: 'Pengkajian Awal Medis Rehabilitasi Medis' },
    })
  }
  if (indexFunctionAssessment > -1) {
    menus.splice(indexFunctionAssessment, 1, {
      ...menus[indexFunctionAssessment],
      component: AssesmentFunctionListAsync,
      props: { encounter: data, type: 'function', label: 'Asesmen Fungsi' },
    })
  }
  if (indexTherapyProtocol > -1) {
    menus.splice(indexTherapyProtocol, 1, {
      ...menus[indexTherapyProtocol],
      component: ProtocolListAsync,
      props: { data: protocolRows, paginationMeta },
    })
  }
  if (indexChemotherapyProtocol > -1) {
    menus.splice(indexChemotherapyProtocol, 1, {
      ...menus[indexChemotherapyProtocol],
      component: ProtocolListAsync,
      props: { data: protocolRows, paginationMeta },
    })
  }
  if (indexChemotherapyMedicine > -1) {
    menus.splice(indexChemotherapyMedicine, 1, {
      ...menus[indexChemotherapyMedicine],
      component: MedicineProtocolListAsync,
      props: { data: protocolRows, paginationMeta },
    })
  }
  if (indexPrescription > -1) {
    menus.splice(indexPrescription, 1, {
      ...menus[indexPrescription],
      component: PrescriptionAsync,
      props: { encounter_id: id }
    })
  }
  if (indexDevice > -1) {
    menus.splice(indexDevice, 1, { ...menus[indexDevice], component: null })
  }
  if (indexMcuRadiology > -1) {
    menus.splice(indexMcuRadiology, 1, {
      ...menus[indexMcuRadiology],
      component: RadiologyAsync,
      props: { encounter_id: id }
    })
  }
  if (indexMcuLabPc > -1) {
    menus.splice(indexMcuLabPc, 1, {
      ...menus[indexMcuLabPc],
      component: CpLabOrderAsync,
      props: { encounter_id: id }
    })
  }
  if (indexMcuLabMicro > -1) {
    menus.splice(indexMcuLabMicro, 1, { ...menus[indexMcuLabMicro], component: null })
  }
  if (indexMcuLabPa > -1) {
    menus.splice(indexMcuLabPa, 1, { ...menus[indexMcuLabPa], component: null })
  }
  if (indexMedicalAction > -1) {
    menus.splice(indexMcuLabPa, 1, { ...menus[indexMcuLabPa], component: null })
  }
  if (indexConsultation > -1) {
    menus.splice(indexConsultation, 1, {
      ...menus[indexConsultation],
      component: ConsultationAsync,
      props: { encounter: data }
    })
  }
  if (indexMcuResult > -1) {
    menus.splice(indexMcuResult, 1, { ...menus[indexMcuResult], component: null })
  }
  if (indexResume > -1) {
    menus.splice(indexResume, 1, { ...menus[indexResume], component: null })
  }
  if (indexControlLetter > -1) {
    menus.splice(indexControlLetter, 1, {
      ...menus[indexControlLetter],
      component: ControlLetterListAsync,
      props: { encounter: data }
    })
  }
  if (indexScreening > -1) {
    menus.splice(indexScreening, 1, { ...menus[indexScreening], component: null })
  }
  if (indexSupportingDocument > -1) {
    menus.splice(indexSupportingDocument, 1, { ...menus[indexSupportingDocument], component: null })
  }
  if (indexPriceList > -1) {
    menus.splice(indexPriceList, 1, { ...menus[indexPriceList], component: null })
  }

  return menus
}

function handleClick(type: string) {
  if (type === 'draft') {
    router.back()
  }
}

watch(getActiveRole, () => {
  const activeRole = getActiveRole()
  activePosition.value = getPositionAs(activeRole)
  menus.value = getMenus()
})

onMounted(async () => {
  await getData()
  menus.value = getMenus()
})
</script>

<template>
  <div class="w-full">
    <div class="mb-4">
      <PubMyUiNavContentBa label="Kembali ke Daftar Kunjungan" @click="handleClick" />
    </div>
    <EncounterPatientInfo v-if="isShowPatient" :data="data" />
    <EncounterHistoryButtonMenu v-if="isShowPatient" />
    <SubMenu :data="menus" :initial-active-menu="activeMenu" @change-menu="activeMenu = $event" />
  </div>
</template>
