<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 { Permission, RoleAccesses, } from '~/models/role'
import { unauthorizedToast } from '~/lib/utils'
import { permissions } from '~/const/page-permission/ambulatory'
import { usePageChecker } from '~/lib/page-checker'
// #endregion


// #region Permission
const roleAccess: RoleAccesses = permissions['/ambulatory/encounter'] || {}
const { getPagePermissions } = useRBAC()
const pagePermission = getPagePermissions(roleAccess)
// #endregion

// #region State
const props = withDefaults(defineProps<{ 
  encounter_id: number
  redirectToForm?: (myRecord_id?: any) => void
}>(), {
  redirectToForm: () => { }
})

const { data, paginationMeta, handlePageChange, handleSearch, searchInput, fetchData } = usePaginatedList({
  fetchFn: (params) => getList({
    'encounter-id': props.encounter_id,
    // 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: () => {
      props.redirectToForm()
    },
   }
}

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){
        props.redirectToForm(recId.value)
      } else {
        unauthorizedToast()
      }
      break

    case ActionEvents.showConfirmDelete:
      if(pagePermission.canDelete){
        isRecordConfirmationOpen.value = true
      } else {
        unauthorizedToast()
      }
      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>
