<script setup lang="ts">
///// Imports
// Pub components
import type { DataTableLoader } from '~/components/pub/my-ui/data-table/type'
import { toast } from '~/components/pub/ui/toast'
import { ActionEvents } from '~/components/pub/my-ui/data/types'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import * as CH from '~/components/pub/my-ui/content-header'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import FileUpload from '~/components/pub/my-ui/form/file-field.vue'
import { useSidebar } from '~/components/pub/ui/sidebar/utils'

// Constants
import { paymentTypes, sepRefTypeCodes } from '~/lib/constants.vclaim'

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

// Services
import {
  getList as getEncounterList,
  remove as removeEncounter,
  cancel as cancelEncounter,
} from '~/services/encounter.service'
import { getValueLabelList as getUnits } from '~/services/unit.service'

// Handlers
import { uploadAttachmentCustom } from '~/handlers/supporting-document.handler'

// Apps
import Content from '~/components/app/encounter/list.vue'
import FilterNav from '~/components/app/encounter/filter-nav.vue'
import FilterForm from '~/components/app/encounter/filter-form.vue'

// Props
const props = defineProps<{
  classCode?: 'ambulatory' | 'emergency' | 'inpatient'
  subClassCode?: 'reg' | 'rehab' | 'chemo' | 'emg' | 'eon' | 'op' | 'icu' | 'hcu' | 'vk'
  canCreate?: boolean
  canUpdate?: boolean
  canDelete?: boolean
}>()

///// Declarations and Flows
// Sidebar automation
const { setOpen } = useSidebar()
setOpen(true)

// Role reactivities
const { getActiveRole } = useUserStore()

// Main data
const data = ref([])
const dataFiltered = ref([])
const filterParams = ref<any>({})
const activeServicePosition = ref(getServicePosition(getActiveRole()))
const isLoading = reactive<DataTableLoader>({
  summary: false,
  isTableLoading: false,
})
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const recSepId = ref<number>(0)
const recSepMenu = ref<string>('')
const recSepSubMenu = ref<string>('')
const isFilterFormDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const isRecordCancelOpen = ref(false)
const uploadFile = ref<any>(null)
const payments = ref<any>([])
const units = ref<any>([])
const sepsList = ref<any>([])

// Headers
const hreaderPrep: CH.Config = {
  title: 'Kunjungan',
  icon: 'i-lucide-users',
  addNav: {
    label: 'Tambah',
    onClick: () => {
      navigateTo(`/${props.classCode}/encounter/add`)
    },
  },
}
if (!props.canCreate) {
  delete hreaderPrep.addNav
}

// Recrod reactivities
provide('activeServicePosition', activeServicePosition)
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('rec_sep_id', recSepId)
provide('rec_sep_menu', recSepMenu)
provide('rec_sep_sub_menu', recSepSubMenu)
provide('table_data_loader', isLoading)

watch(getActiveRole, (role?: string) => {
  activeServicePosition.value = getServicePosition(role)
})

watch(
  () => recAction.value,
  () => {
    const basePath = `/${props.classCode}/encounter`
    if (recAction.value === ActionEvents.showConfirmDelete) {
      isRecordConfirmationOpen.value = true
    } else if (recAction.value === ActionEvents.showCancel) {
      isRecordCancelOpen.value = true
    } else if (recAction.value === ActionEvents.showDetail) {
      navigateTo(`${basePath}/${recId.value}/detail`)
    } else if (recAction.value === ActionEvents.showEdit) {
      navigateTo(`${basePath}/${recId.value}/edit`)
    } else if (recAction.value === ActionEvents.showProcess) {
      navigateTo(`${basePath}/${recId.value}/process`)
    } else if (recAction.value === ActionEvents.showConfirmDelete) {
      isRecordConfirmationOpen.value = true
    }
    recAction.value = '' // reset
  },
)

watch([recSepId, recSepMenu, recSepSubMenu], (value) => {
  const id = value[0]
  const menu = value[1]
  const subMenu = value[2]
  if (!id) return
  if (subMenu === 'view') {
    handleViewFile(id, menu, subMenu)
  }
  if (subMenu === 'edit') {
    handleUploadFile(id, menu)
  }
})

onMounted(async () => {
  getPatientList()
  units.value = await getUnits({}, true)
  payments.value = Object.keys(paymentTypes).map((item) => ({
    value: item.toString(),
    label: paymentTypes[item],
  })) as any
  sepsList.value = Object.keys(sepRefTypeCodes).map((item) => ({
    value: item.toString(),
    label: sepRefTypeCodes[item],
  })) as any
})

/////// Functions
async function getPatientList() {
  isLoading.isTableLoading = true
  const includesParamsArrays = [
    'patient',
    'patient-person',
    'patient-person-addresses',
    'Appointment_Doctor',
    'Appointment_Doctor-employee',
    'Appointment_Doctor-employee-person',
    'Responsible_Doctor',
    'Responsible_Doctor-employee',
    'Responsible_Doctor-employee-person',
    'EncounterDocuments',
    'unit',
    'vclaimReference', // vclaimReference | vclaimSep
  ]
  const includesParams = includesParamsArrays.join(',')
  data.value = []
  try {
    const params: any = { includes: includesParams, ...filterParams.value }
    if (props.classCode) {
      params['class-code'] = props.classCode
    }
    if (props.subClassCode) {
      params['sub-class-code'] = props.subClassCode
    }
    const result = await getEncounterList(params)
    if (result.success) {
      data.value = result.body?.data || []
      dataFiltered.value = [...data.value]
    }
  } catch (error) {
    console.error('Error fetching encounter list:', error)
  } finally {
    isLoading.isTableLoading = false
  }
}

function handleUploadFile(id: number, menu: string) {
  uploadFile.value = null
  const fileInput: HTMLInputElement | undefined | null = document
    .getElementById('uploadFile')
    ?.querySelector("input[type='file']")
  if (fileInput) {
    fileInput.value = ''
    fileInput.click()
  }
}

async function handleUploadFileSubmit() {
  if (!uploadFile.value) return
  const result = await uploadAttachmentCustom({
    file: uploadFile.value,
    refId: recSepId.value,
    entityTypeCode: 'encounter',
    type: recSepMenu.value === 'sep' ? 'vclaim-sep' : 'vclaim-sipp',
  })
  if (result.success) {
    toast({
      title: 'Berhasil',
      description: 'File berhasil diunggah',
      variant: 'default',
    })
    await getPatientList()
  } else {
    toast({
      title: 'Gagal',
      description: 'File gagal diunggah',
      variant: 'destructive',
    })
  }
}

function handleViewFile(id: number, menu: string, subMenu: string) {
  const currentData: any = data.value.find((item: any) => Number(item.id) === Number(id))
  console.log(currentData)
  if (!currentData) return
  let fileReviewSep: any = null
  let fileReviewSipp: any = null
  for (const doc of currentData.encounterDocuments) {
    if (doc.type_code === 'vclaim-sep') {
      fileReviewSep = { id: doc.id, fileName: doc.fileName, filePath: doc.filePath, type: doc.type_code }
    } else if (doc.type_code === 'vclaim-sipp') {
      fileReviewSipp = { id: doc.id, fileName: doc.fileName, filePath: doc.filePath, type: doc.type_code }
    }
  }
  if (fileReviewSep && menu === 'sep' && subMenu === 'view') {
    window.open(fileReviewSep.filePath, '_blank')
  }
  if (fileReviewSipp && menu === 'sipp' && subMenu === 'view') {
    window.open(fileReviewSipp.filePath, '_blank')
  }
}

function handleFilterApply(filters: { personName: string; startDate: string; endDate: string }) {
  filterParams.value = {
    // 'person-name': filters.personName,
    'patient-identifier': filters.personName,
    'start-date': filters.startDate,
    'end-date': filters.endDate,
  }
  getPatientList()
}

function handleFilterReset() {
  isFilterFormDialogOpen.value = false
  filterParams.value = {}
  getPatientList()
}

function handleFilterSearch(filters: any) {
  isFilterFormDialogOpen.value = false
  filterParams.value = { ...filterParams.value, ...filters }
  getPatientList()
}

// Handle confirmation result
async function handleConfirmCancel(record: any, action: string) {
  if (action === 'deactivate' && record?.id) {
    try {
      const result = await cancelEncounter(record.id)
      if (result.success) {
        toast({
          title: 'Berhasil',
          description: 'Kunjungan berhasil dibatalkan',
          variant: 'default',
        })
        await getPatientList() // Refresh list
      } else {
        const errorMessage = result.body?.message || 'Gagal membatalkan kunjungan'
        toast({
          title: 'Gagal',
          description: errorMessage,
          variant: 'destructive',
        })
      }
    } catch (error: any) {
      console.error('Error cancellation encounter:', error)
      toast({
        title: 'Gagal',
        description: error?.message || 'Gagal membatalkan kunjungan',
        variant: 'destructive',
      })
    } finally {
      // Reset state
      recId.value = 0
      recAction.value = ''
      recItem.value = null
      isRecordCancelOpen.value = false
    }
  }
}

// Handle confirmation result
async function handleConfirmDelete(record: any, action: string) {
  if (action === 'delete' && record?.id) {
    try {
      const result = await removeEncounter(record.id)
      if (result.success) {
        toast({
          title: 'Berhasil',
          description: 'Kunjungan berhasil dihapus',
          variant: 'default',
        })
        await getPatientList() // Refresh list
      } else {
        const errorMessage = result.body?.message || 'Gagal menghapus kunjungan'
        toast({
          title: 'Gagal',
          description: errorMessage,
          variant: 'destructive',
        })
      }
    } catch (error: any) {
      console.error('Error deleting encounter:', error)
      toast({
        title: 'Gagal',
        description: error?.message || 'Gagal menghapus kunjungan',
        variant: 'destructive',
      })
    } finally {
      // Reset state
      recId.value = 0
      recAction.value = ''
      recItem.value = null
      isRecordConfirmationOpen.value = false
    }
  }
}

function handleCancelConfirmation() {
  // Reset record state when cancelled
  recId.value = 0
  recAction.value = ''
  recItem.value = null
  isRecordCancelOpen.value = false
}

function handleRemoveConfirmation() {
  // Reset record state when cancelled
  recId.value = 0
  recAction.value = ''
  recItem.value = null
  isRecordConfirmationOpen.value = false
}
</script>

<template>
  <CH.ContentHeader v-bind="hreaderPrep">
    <FilterNav
      :active-positon="activeServicePosition"
      :enable-export="false"
      @apply="handleFilterApply"
      @click="() => (isFilterFormDialogOpen = true)"
      @onExportPdf="() => {}"
      @onExportExcel="() => {}"
      @nExportCsv="() => {}"
    />
  </CH.ContentHeader>

  <Content
    :data="data"
    :class-code="classCode"
  />

  <!-- Filter -->
  <Dialog
    v-model:open="isFilterFormDialogOpen"
    title="Filter Data"
    size="lg"
    prevent-outside
  >
    <FilterForm
      :payments="payments"
      :units="units"
      :visits="sepsList"
      @search="handleFilterSearch"
      @reset="handleFilterReset"
    />
  </Dialog>

  <!-- Batal -->
  <RecordConfirmation
    v-if="canDelete"
    v-model:open="isRecordCancelOpen"
    custom-title="Batalkan Kunjungan"
    custom-message="Apakah anda yakin ingin membatalkan kunjungan pasien berikut?"
    action="deactivate"
    :record="recItem"
    @confirm="handleConfirmCancel"
    @cancel="handleCancelConfirmation"
  >
    <template #default="{ record }">
      <div class="text-sm">
        <p v-if="record?.patient?.person?.name">
          <strong>Nama:</strong>
          {{ record.patient.person.name }}
        </p>
        <p v-if="record?.medical_record_number">
          <strong>No RM:</strong>
          {{ record.medical_record_number }}
        </p>
      </div>
    </template>
  </RecordConfirmation>

  <!-- Hapus -->
  <RecordConfirmation
    v-if="canDelete"
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="handleConfirmDelete"
    @cancel="handleRemoveConfirmation"
  >
    <template #default="{ record }">
      <div class="text-sm">
        <p>
          <strong>ID:</strong>
          {{ record?.id }}
        </p>
        <p v-if="record?.patient?.person?.name">
          <strong>Pasien:</strong>
          {{ record.patient.person.name }}
        </p>
        <p v-if="record?.class_code">
          <strong>Kelas:</strong>
          {{ record.class_code }}
        </p>
      </div>
    </template>
  </RecordConfirmation>
  <Dialog
    title="Hapus data"
    size="md"
    v-model:open="isRecordConfirmationOpen"
  >
    Hak akses tidak memenuhi kriteria untuk proses ini.
  </Dialog>

  <FileUpload
    class="hidden"
    field-name="uploadFile"
    label="Dokumen"
    placeholder="Pilih file"
    :accept="['pdf', 'jpg', 'png']"
    :max-size-mb="1"
    v-model="uploadFile"
    @file-selected="handleUploadFileSubmit"
  />
</template>
