<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 { useSidebar } from '~/components/pub/ui/sidebar/utils'

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

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

// 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 isFilterFormDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const isRecordCancelOpen = ref(false)

// 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
}

// Filters
const filter = ref<{
  installation: {
    msg: {
      placeholder: string
    }
    items: {
      value: string
      label: string
      code: string
    }[]
  }
  schema: any
  initialValues?: Partial<any>
  errors?: any
}>({
  installation: {
    msg: {
      placeholder: 'Pilih',
    },
    items: [],
  },
  schema: {},
})

// Recrod reactivities
provide('activeServicePosition', activeServicePosition)
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
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
  },
)

onMounted(() => {
  getPatientList()
})

/////// Functions
async function getPatientList() {
  isLoading.isTableLoading = true
  const includesParams =
    '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'
  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 handleFilterApply(filters: { personName: string; startDate: string; endDate: string }) {
  filterParams.value = {
    'person-name': filters.personName,
    'start-date': filters.startDate,
    'end-date': filters.endDate,
  }
  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"
      @apply="handleFilterApply"
      @onExportPdf="() => {}"
      @onExportExcel="() => {}"
      @nExportCsv="() => {}"
    />
  </CH.ContentHeader>

  <Content :data="data" />

  <!-- Filter -->
  <Dialog
    v-model:open="isFilterFormDialogOpen"
    title="Filter"
    size="lg"
    prevent-outside
  >
    <FilterForm v-bind="filter" />
  </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>
</template>
