<script setup lang="ts">
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/data/types'

// #region Imports
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import { ActionEvents } from '~/components/pub/my-ui/data/types'

import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { getList, remove } from '~/services/control-letter.service'
import { toast } from '~/components/pub/ui/toast'
import type { Encounter } from '~/models/encounter'
import WarningAlert from '~/components/pub/my-ui/alert/warning-alert.vue'
// #endregion

// #region State
const props = defineProps<{
  encounter?: Encounter
}>()
const route = useRoute()
const encounterId = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0

const { data, isLoading, paginationMeta, searchInput, handlePageChange, handleSearch, fetchData } = usePaginatedList({
  fetchFn: (params) => getList({ ...params, includes: 'specialist,subspecialist,doctor-employee-person', }),
  entityName: 'control-letter',
})

const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
  },
  onInput: (val: string) => {
    searchInput.value = val
  },
  onClear: () => {
    searchInput.value = ''
  },
}

const isRecordConfirmationOpen = ref(false)
const summaryLoading = ref(false)
const isRequirementsMet = ref(true)

const recId = ref<number>(0)
const recAction = ref<string>('')
const recItem = ref<any>(null)

const headerPrep: HeaderPrep = {
  title: "Surat Kontrol",
  icon: 'i-lucide-newspaper',
  addNav: {
    label: "Surat Kontrol",
    onClick: () => navigateTo({
        name: 'rehab-encounter-id-control-letter-add',
        params: { id: encounterId },
      }),
  },
}
// #endregion

// #region Lifecycle Hooks
onMounted(() => {
  getListData()
})
// #endregion

// #region Functions
async function getListData() {
  try {
    summaryLoading.value = true
    await new Promise((resolve) => setTimeout(resolve, 500))
  } catch (error) {
    console.error('Error fetching Data:', error)
  } finally {
    summaryLoading.value = false
  }
}

// Handle confirmation result
async function handleConfirmDelete(record: any, action: string) {
  if (action === 'delete' && record?.id) {
    try {
      const result = await remove(record.id)
      if (result.success) {
        toast({ title: 'Berhasil', description: 'Data berhasil dihapus', variant: 'default' })
        await fetchData()
      } else {
        toast({ title: 'Gagal', description: `Data gagal dihapus`, variant: 'destructive' })
      }
    } catch (error) {
      toast({ title: 'Gagal', description: `Something went wrong`, variant: 'destructive' })
    }
  }
}

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

// #region Provide
provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
// #endregion

// #region Watchers
watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      navigateTo({
        name: 'rehab-encounter-id-control-letter-control_letter_id',
        params: { id: encounterId, "control_letter_id": recId.value },
      })
      break

    case ActionEvents.showEdit:
      // TODO: Handle edit action
      // isFormEntryDialogOpen.value = true
      navigateTo({
        name: 'rehab-encounter-id-control-letter-control_letter_id-edit',
        params: { id: encounterId, "control_letter_id": recId.value },
      })
      break

    case ActionEvents.showConfirmDelete:
      // Trigger confirmation modal open
      isRecordConfirmationOpen.value = true
      break
  }
})
// #endregion
</script>

<template>
  <WarningAlert v-if="!isRequirementsMet"
    class="mb-5"
    text="Syarat pembuatan surat kontrol belum terpenuhi"
    :description="[
      'Lanjutan Penatalaksanaan Pasien harus pulang/KRS.',
      'Status Resume Medis harus tervalidasi.'
    ]" />

  <div v-else>
    <Header v-model:search="searchInput"
      :prep="{ ...headerPrep }"
      :ref-search-nav="refSearchNav"
      @search="handleSearch" />

    <AppControlLetterList :data="data" :pagination-meta="paginationMeta" @page-change="handlePageChange" />

    <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?.firstName">
            <strong>Nama:</strong>
            {{ record.firstName }}
          </p>
          <p v-if="record?.code">
            <strong>Kode:</strong>
            {{ record.cellphone }}
          </p>
        </div>
      </template>
    </RecordConfirmation>
  </div>
</template>
