<script setup lang="ts">
// Components
import { Calendar, Hospital, UserCheck, UsersRound } from 'lucide-vue-next'
import SummaryCard from '~/components/pub/my-ui/summary-card/summary-card.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import Filter from '~/components/pub/my-ui/nav-header/filter.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

// Types
import type { DataTableLoader } from '~/components/pub/my-ui/data-table/type'
import type { Summary } from '~/components/pub/my-ui/summary-card/type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/data/types'
import { ActionEvents } from '~/components/pub/my-ui/data/types'

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

// UI
import { toast } from '~/components/pub/ui/toast'

const props = defineProps<{
  classCode?: 'ambulatory' | 'emergency' | 'inpatient' | 'outpatient'
  subClassCode?: 'reg' | 'rehab' | 'chemo' | 'emg' | 'eon' | 'op' | 'icu' | 'hcu' | 'vk'
  type: string
}>()

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 hreaderPrep: HeaderPrep = {
  title: 'Kunjungan',
  icon: 'i-lucide-users',
  addNav: {
    label: 'Tambah',
    onClick: () => {
      if (props.classCode === 'ambulatory' && props.subClassCode === 'rehab') {
        navigateTo('/rehab/encounter/add')
      }
      if (props.classCode === 'ambulatory' && props.subClassCode === 'reg') {
        navigateTo('/outpatient/encounter/add')
      }
      if (props.classCode === 'emergency') {
        navigateTo('/emergency/encounter/add')
      }
      if (props.classCode === 'inpatient') {
        navigateTo('/inpatient/encounter/add')
      }
    },
  },
}

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

// Loading state management

/**
 * Get base path for encounter routes based on classCode and subClassCode
 */
function getBasePath(): string {
  if (props.classCode === 'ambulatory' && props.subClassCode === 'rehab') {
    return '/rehab/encounter'
  }
  if (props.classCode === 'ambulatory' && props.subClassCode === 'reg') {
    return '/outpatient/encounter'
  }
  if (props.classCode === 'emergency') {
    return '/emergency/encounter'
  }
  if (props.classCode === 'inpatient') {
    return '/inpatient/encounter'
  }
  return '/encounter' // fallback
}

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 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
  isRecordConfirmationOpen.value = false
}

watch(
  () => recAction.value,
  () => {
    if (recAction.value === ActionEvents.showConfirmDelete) {
      isRecordConfirmationOpen.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}/edit`)
      } else if (recAction.value === 'showProcess') {
        navigateTo(`${basePath}/${recId.value}/process`)
      } 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
      }
    }
  },
)

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

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

<template>
  <Header
    :prep="{ ...hreaderPrep }"
    :ref-search-nav="refSearchNav"
  />
  <Separator class="my-4 xl:my-5" />

  <Filter
    :prep="hreaderPrep"
    :ref-search-nav="refSearchNav"
  />

  <AppEncounterList :data="data" />

  <Dialog
    v-model:open="isFormEntryDialogOpen"
    title="Filter"
    size="lg"
    prevent-outside
  >
    <AppEncounterFilter
      :installation="{
        msg: { placeholder: 'Pilih' },
        items: [],
      }"
      :schema="{}"
    />
  </Dialog>

  <!-- Record Confirmation Modal -->
  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="handleConfirmDelete"
    @cancel="handleCancelConfirmation"
  >
    <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>
</template>
