<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 Filter from '~/components/pub/my-ui/nav-header/filter.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import { usePaginatedList } from '~/composables/usePaginatedList'
import { getList, remove } from '~/services/prb.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'
import type { Prb } from '~/models/prb'
import DocPreviewDialog from '~/components/pub/my-ui/modal/doc-preview-dialog.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
// #endregion

// #region State
const props = withDefaults(defineProps<{
  encounter?: Encounter
  isBpjs?: boolean
}>(), {
  isBpjs: false,
})
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: '', }),
  entityName: 'prb',
})
const prbHistory = usePaginatedList({
  fetchFn: (params) => getList({ ...params }),
  entityName: 'prb-history',
})
const dummy = [
  {
    "id": 1,
    "date": new Date().toISOString(),
    "name1": "Dr. Smith",
    "name2": "Maria S.",
    "name3": "Project Alpha",
    "name4": "Completed",
    "name5": 95.5
  },
]

const isHistoryDialogOpen = ref(false)
const isDocPreviewDialogOpen = ref(false)
const isFilterDialogOpen = ref(false)
const isRecordConfirmationOpen = ref(false)
const summaryLoading = ref(false)
const isRequirementsMet = ref(true)
const Prb = ref<Prb | null>(null)

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

const headerPrep: HeaderPrep = {
  title: "Program Rujuk Balik",
  icon: 'i-lucide-history',
}
if(true){
  headerPrep.addNav = {
    label: "Program Rujuk Balik",
    onClick: () => navigateTo({
        name: 'integration-bpjs-prb-add',
      }),
  };
}
headerPrep.components = [
  {
    component: defineAsyncComponent(() => import('~/components/app/prb/_common/btn-history.vue')),
    props: {  }
  },
];
const refSearchNav: RefSearchNav = {
  onClick: () => {
    isFilterDialogOpen.value = true
  },
  onInput: (val: string) => {
    searchInput.value = val
  },
  onClear: () => {
    searchInput.value = ''
  },
}
// #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
  }
}
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
}

function handleFiltering() {
  isFilterDialogOpen.value = false
}
// #endregion

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

// #region Watchers
watch([recId, recAction, timestamp], () => {
  switch (recAction.value) {
    case ActionEvents.showEdit:
      navigateTo({
        name: 'integration-bpjs-prb-prb_id-edit',
        params: { id: encounterId, "prb_id": recId.value },
      })
      break

    case ActionEvents.showPrint:
      isDocPreviewDialogOpen.value = true      
      break

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

<template>
  <WarningAlert v-if="!isRequirementsMet"
    class="mb-5"
    text="Syarat pembuatan PRB belum terpenuhi"
    :description="[
      'Lanjutan Penatalaksanaan Pasien harus terisi Dirujuk Eksternal',
      'Jenis Pembayaran pasien harus JKN'
    ]" />

  <div v-else>
    <Header :prep="headerPrep" />

    <Filter
      :prep="headerPrep"
      :ref-search-nav="refSearchNav"
      :enable-export="false"
    />

    <AppPrbList :is-bpjs="true" :data="dummy" />

    <Dialog v-model:open="isHistoryDialogOpen" title="History" size="full">
      <AppPrbHistoryList
        :data="dummy"
        :pagination-meta="prbHistory.paginationMeta"
        @page-change="prbHistory.handlePageChange" />
    </Dialog>

    <Dialog v-model:open="isFilterDialogOpen" title="Filter" size="lg">
      <AppPrbCommonFilter @submit="handleFiltering" />
    </Dialog>

    <Dialog v-model:open="isDocPreviewDialogOpen" title="Preview Dokumen" size="2xl">
      <DocPreviewDialog :link="`https://www.antennahouse.com/hubfs/xsl-fo-sample/pdf/basic-link-1.pdf`" />
    </Dialog>

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