<script setup lang="ts">
// #region Imports
import { ActionEvents } from '~/components/pub/my-ui/data/types'
import type { HeaderPrep, RefSearchNav, } from '~/components/pub/my-ui/data/types'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import { getList, remove } from '~/services/supporting-document.service'
import { toast } from '~/components/pub/ui/toast'
import type { Encounter } from '~/models/encounter'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import DocPreviewDialog from '~/components/pub/my-ui/modal/doc-preview-dialog.vue'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import type { PagePermission } from '~/models/role'
import { PAGE_PERMISSIONS } from '~/lib/page-permission'
import { unauthorizedToast } from '~/lib/utils'
// #endregion


// #region Permission
const roleAccess: PagePermission = PAGE_PERMISSIONS['/rehab/encounter']
const { getPagePermissions } = useRBAC()
const pagePermission = getPagePermissions(roleAccess)

const {user,userRole} = useUserStore()
const {getUserPermissions} = useRBAC()
// #endregion

// #region State
const props = defineProps<{
  encounter?: Encounter
  refresh: () => void
}>()

const route = useRoute()
const encounterId = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0

const { data, paginationMeta, handlePageChange, handleSearch, searchInput, fetchData } = usePaginatedList({
  fetchFn: (params) => getList({
    'encounter-id': encounterId,
    // includes: "employee",
    ...params,
  }),
  entityName: 'encounter-document',
})

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

const headerPrep: HeaderPrep = {
  title: "Upload Dokumen",
  icon: 'i-lucide-newspaper',
}
if (pagePermission.canCreate) {
  headerPrep.addNav = {
    label: "Upload Dokumen",
    onClick: () => navigateTo({
        name: 'rehab-encounter-id-document-upload-add',
        params: { id: encounterId },
      }),
   }
}

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

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

// #region Functions

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' })
        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('timestamp', timestamp)
// #endregion

// #region Watchers
watch([recId, recAction, timestamp], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      isDocPreviewDialogOpen.value = true
      break
    case ActionEvents.showEdit:
      if(pagePermission.canUpdate){
        navigateTo({
          name: 'rehab-encounter-id-document-upload-document_id-edit',
          params: { id: encounterId, "document_id": recId.value },
        })
      } else {
        unauthorizedToast()
      }
      break
    case ActionEvents.showConfirmDelete:
      if(pagePermission.canDelete){
        isRecordConfirmationOpen.value = true
      } else {
        unauthorizedToast()
      }
      navigateTo(recItem.value.filePath, { external: true, open: { target: '_blank' } })
      break
    case ActionEvents.showEdit:
      navigateTo({
        name: 'rehab-encounter-id-document-upload-document_id-edit',
        params: { id: encounterId, "document_id": recId.value },
      })
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})
// #endregion
</script>

<template>
  <Header :prep="{ ...headerPrep }"
      v-model:search="searchInput"
      :ref-search-nav="refSearchNav"
      @search="handleSearch"
  />
  <AppDocumentUploadList :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?.name">
            <strong>Nama:</strong>
            {{ record?.name }}
          </p>
        </div>
      </template>
    </RecordConfirmation>

  <Dialog v-model:open="isDocPreviewDialogOpen" title="Preview Dokumen" size="2xl">
    <DocPreviewDialog :link="recItem?.filePath" />
  </Dialog>
</template>
