<script setup lang="ts">
// Libs
import { getPositionAs } from '~/lib/roles'

// Types
// Pub components
import type { DataTableLoader } from '~/components/pub/my-ui/data-table/type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/nav-header/index'
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 Header from '~/components/pub/my-ui/nav-header/prep.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'

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

//
const { setOpen } = useSidebar()
setOpen(true)

const { getActiveRole } = useUserStore()
const activeRole = getActiveRole()
const activePosition = ref(getPositionAs(activeRole))


// Main data
const data = ref([])
const isLoading = reactive<DataTableLoader>({
  summary: false,
  isTableLoading: false,
})
const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)
const isFormEntryDialogOpen = 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
}

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: {},
})

const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
    isFormEntryDialogOpen.value = true
  },
  onInput: (_val: string) => {
    // filter patient list
  },
  onClear: () => {
    // clear url param
  },
}

// Reactivities
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)

watch(() => recAction.value, () => {
  const basePath = `/${props.classCode}/encounter`
  if (recAction.value === ActionEvents.showDetail) {
    navigateTo(`${basePath}/${recId.value}`)
  } 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
  try {
    const params: any = { includes: 'patient,patient-person' }
    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 || []
    }
  } catch (error) {
    console.error('Error fetching encounter list:', error)
  } finally {
    isLoading.isTableLoading = false
  }
}

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

watch(
  () => recAction.value,
  () => {
    if (recAction.value === ActionEvents.showConfirmDelete) {
      isRecordConfirmationOpen.value = true
      return
    }

    if (recAction.value === ActionEvents.showCancel) {
      isRecordCancelOpen.value = true
      return
    }

    const basePath = getBasePath()

    if (props.type === 'encounter') {
      if (recAction.value === 'showDetail') {
        navigateTo(`${basePath}/${recId.value}/detail`)
      } else if (recAction.value === 'showEdit') {
        navigateTo(`${basePath}/${recId.value}/process`)
      } else if (recAction.value === 'showPrint') {
        console.log('print')
      } else {
        // handle other actions
      }
    } else if (props.type === 'registration') {
      // Handle registration type if needed
      if (recAction.value === 'showDetail') {
        navigateTo(`${basePath.replace('/encounter', '/registration')}/${recId.value}/detail`)
      } else if (recAction.value === 'showEdit') {
        navigateTo(`${basePath.replace('/encounter', '/registration')}/${recId.value}/edit`)
      } else if (recAction.value === 'showProcess') {
        navigateTo(`${basePath.replace('/encounter', '/registration')}/${recId.value}/process`)
      } else {
        // handle other actions
      }
    }
  },
)

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

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
provide('position', activePosition)

onMounted(() => {
  getPatientList()
})
</script>

<template>
  <CH.ContentHeader v-bind="hreaderPrep">
    <FilterNav  />
  </CH.ContentHeader>

  <Content :data="data" />

  <Dialog
    v-model:open="isFormEntryDialogOpen"
    title="Filter"
    size="lg"
    prevent-outside
  >
    <FilterForm v-bind="filter"  />
  </Dialog>

  <!-- Record Confirmation Modal -->
   <RecordConfirmation
    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>

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