<script setup lang="ts">
import { computed } from 'vue'
///// Imports
// Pubs components
import ContentSwitcher from '~/components/pub/my-ui/content-switcher/content-switcher.vue'
import { useSidebar } from '~/components/pub/ui/sidebar/utils'
import SubMenu from '~/components/pub/my-ui/menus/submenu.vue'
import ContentNavBa from '~/components/pub/my-ui/nav-content/ba.vue'

// App libs
import { getServicePosition } from '~/lib/roles' // previously getPositionAs

// App Models
import { genEncounter, type Encounter } from '~/models/encounter'

// Handlers
import type { EncounterProps } from '~/handlers/encounter-init.handler'
import { getEncounterData } from '~/handlers/encounter-process.handler'
import { getMenuItems } from '~/handlers/encounter-init.handler'

// PLASE ORDER BY TAB POSITION
import Status from '~/components/content/encounter/status.vue'
import AssesmentFunctionList from '~/components/content/soapi/entry.vue'
import EarlyMedicalAssesmentList from '~/components/content/soapi/entry.vue'
import EarlyMedicalRehabList from '~/components/content/soapi/entry.vue'
import DeviceOrder from '~/components/content/device-order/main.vue'
import Prescription from '~/components/content/prescription/main.vue'
import CpLabOrder from '~/components/content/cp-lab-order/main.vue'
import Radiology from '~/components/content/radiology-order/main.vue'
import Consultation from '~/components/content/consultation/list.vue'
import Cprj from '~/components/content/cprj/entry.vue'
import DocUploadList from '~/components/content/document-upload/list.vue'
import GeneralConsentList from '~/components/content/general-consent/entry.vue'
import ResumeList from '~/components/content/resume/list.vue'
import ControlLetterList from '~/components/content/control-letter/list.vue'
import InitialNursingStudy from '~/components/content/initial-nursing/entry.vue'
// App Components
import EncounterPatientInfo from '~/components/app/encounter/quick-info.vue'
import EncounterHistoryButtonMenu from '~/components/app/encounter/quick-shortcut.vue'

///// Declarations and Flows
// Props
const props = defineProps<{
  classCode: EncounterProps['classCode']
  subClassCode?: EncounterProps['subClassCode']
  canCreate?: boolean
  canRead?: boolean
  canUpdate?: boolean
  canDelete?: boolean
}>()

// Common preparations
const route = useRoute()
const router = useRouter()

const { user, userActiveRole, getActiveRole } = useUserStore()
const activeRole = getActiveRole()
const activePosition = ref(getServicePosition(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<Encounter>(genEncounter())
const isShowPatient = computed(() => data.value && data.value?.patient?.person)

const { setOpen } = useSidebar()
setOpen(false)

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: '',
  },
  {
    value: 'rehab-medical-assessment',
    label: 'Pengkajian Awal Medis Rehabilitasi Medis',
    component: EarlyMedicalRehabList,
    props: { encounter: data, type: 'early-rehab', label: 'Pengkajian Awal Medis Rehabilitasi Medis' },
  },
  {
    value: 'function-assessment',
    label: 'Asesmen Fungsi',
    component: AssesmentFunctionList,
    props: { encounter: data, type: 'function', label: 'Asesmen Fungsi' },
  },
  { value: 'therapy-protocol', label: 'Protokol Terapi' },
  { value: 'education-assessment', label: 'Asesmen Kebutuhan Edukasi' },
  { value: 'patient-note', label: 'CPRJ', component: Cprj, props: { encounter: data } },
  { value: 'consent', label: 'General Consent', component: GeneralConsentList, props: { encounter: data } },
  {
    value: 'initial-nursing-study',
    label: 'Kajian Awal Keperawatan',
    component: InitialNursingStudy,
    props: { encounter: data },
  },
  { value: 'prescription', label: 'Order Obat', component: Prescription, props: { encounter_id: data.value.id } },
  { value: 'device-order', label: 'Order Alkes', component: DeviceOrder, props: { encounter_id: data.value.id } },
  { value: 'device', label: 'Order Alkes' },
  { value: 'mcu-radiology', label: 'Order Radiologi', component: Radiology, props: { encounter_id: data.value.id } },
  { value: 'mcu-lab-cp', label: 'Order Lab PK', component: CpLabOrder, props: { encounter_id: data.value.id } },
  { value: 'mcu-lab-micro', label: 'Order Lab Mikro' },
  { value: 'mcu-lab-pa', label: 'Order Lab PA' },
  { value: 'medical-action', label: 'Order Ruang Tindakan' },
  { value: 'mcu-result', label: 'Hasil Penunjang' },
  { value: 'consultation', label: 'Konsultasi', component: Consultation, props: { encounter: data } },
  { value: 'resume', label: 'Resume', component: ResumeList, props: { encounter: data } },
  { value: 'control', label: 'Surat Kontrol', component: ControlLetterList, props: { encounter: data } },
  { value: 'screening', label: 'Skrinning MPP' },
  {
    value: 'supporting-document',
    label: 'Upload Dokumen Pendukung',
    component: DocUploadList,
    props: { encounter: data },
    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,
}

// Reacrtivities
watch(getActiveRole, () => {
  activePosition.value = getServicePosition(userActiveRole)
  initMenus()
})

onMounted(async () => {
  await getData()
  initMenus()
})

///// Functions
function handleClick(type: string) {
  if (type === 'draft') {
    router.push(`/${props.classCode}/encounter`)
  }
}

function initMenus() {
  menus.value = getMenuItems(
    id,
    props,
    user,
    {
      encounter: data.value,
    } as any,
    {
      protocolTheraphy: paginationMeta,
      protocolChemotherapy: paginationMeta,
      medicineProtocolChemotherapy: paginationMeta,
    },
  )
}

async function getData() {
  data.value = await getEncounterData(id)
}
</script>

<template>
  <div class="w-full">
    <div class="bg-white dark:bg-slate-800">
      <div class="p-3 2xl:p-4 border-b border-slate-300  dark:border-slate-700">
        <ContentNavBa label="Kembali Ke Daftar" @click="handleClick" />
      </div>
      <ContentSwitcher :active="1" class="h-[130px] 2xl:h-[160px]">
        <template v-slot:content1>
          <EncounterPatientInfo v-if="isShowPatient" :data="data" />
        </template>
        <template v-slot:content2>
          <EncounterHistoryButtonMenu v-if="isShowPatient" />
        </template>
      </ContentSwitcher>
    </div>
    <SubMenu
      :data="menus"
      :initial-active-menu="activeMenu"
      @change-menu="activeMenu = $event"
      :can-create="canCreate"
      :can-read="canRead"
      :can-update="canUpdate"
      :can-delete="canDelete"
    />
  </div>
</template>
