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

// #region Imports
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/kfr.service'
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Action from '~/components/pub/my-ui/nav-footer/ba-dr-su.vue'
import type { Encounter } from '~/models/encounter'
import { cn } from '~/lib/utils'
import type { ExposedForm } from '~/types/form'
import { VerificationSchema } from '~/schemas/verification.schema'
import { handleActionSave } from '~/handlers/kfr.handler'
import { toast } from '~/components/pub/ui/toast'
import DocPreviewDialog from '~/components/pub/my-ui/modal/doc-preview-dialog.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import { CalendarDate } from '@internationalized/date'
import type { DateRange } from 'radix-vue'
import Confirmation from '~/components/pub/my-ui/confirmation/confirmation.vue'
// #endregion

// Props
interface Props {
  encounter: Encounter
}
const props = defineProps<Props>()
const route = useRoute()
const encounterId = typeof route.params.id == 'string' ? parseInt(route.params.id) : 0
const kfrId = typeof route.params.kfr_id == 'string' ? parseInt(route.params.kfr_id) : 0
// #endregion

// #region State
const { getActiveRole } = useUserStore()
const isVerifyDialogOpen = ref(false)
const isValidateDialogOpen = ref(false)
const isHistoryDialogOpen = ref(false)
const isPatientInTherapy = ref(false)
const { data, isLoading, paginationMeta, searchInput, handlePageChange, handleSearch, fetchData } = usePaginatedList({
  fetchFn: (params) => getList({ ...params }),
  entityName: 'kfr',
})
const historyData = usePaginatedList({
  fetchFn: (params) => getList({ ...params }),
  entityName: 'kfr-history',
})

const dummy = [
  {
    id: 11,
    date: new Date(),
    result: {
      s: `Example`,
      o: `Example`,
      a: `Example`,
      p: {
        goal: `Example`,
        action: `Example`,
        education: `Example`,
        frequency: `Example`,
      },
      plan: `Example`,
      planDesc: `Description`,
    },
    type: `Asesmen`,
    status: {
      verified: 1,
      validated: 0,
    },
  }
]

const isRecordConfirmationOpen = ref(false)
const isDocPreviewDialogOpen = ref(false)
const summaryLoading = ref(false)

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

const isAssessment = ref<boolean>(false)
const isTherapyProtocol = ref<boolean>(false)
const isReassessment = ref<boolean>(true)
const isInOrBeyondAssessmentPeriod = ref<boolean>(true)

const isDoctor = computed(() => getActiveRole() === 'emp|doc')
const isAdmin = computed(() => getActiveRole() === 'system')

const isCaptchaValid = ref(false)
provide('isCaptchaValid', isCaptchaValid)

const addBtnTxt = computed(() => {
  if (isAssessment.value) {
    return `Tambah Asesmen`
  } else if (isTherapyProtocol.value) {
    return `Tambah Protokol Terapi`
  } else if (isReassessment.value) {
    return `Tambah Re-Asesmen`
  }
  return `Tambah Asesmen`
})

  const headerPrep: HeaderPrep = {
    title: "Formulir Rawat Jalan KFR",
    icon: 'i-lucide-newspaper',
  }
if(isDoctor.value || isAdmin.value) {
  headerPrep.addNav = {
    label: addBtnTxt.value,
    onClick: () => navigateTo({
      name: 'rehab-encounter-id-kfr-add',
    }),
  }
}
if(!isAssessment.value) {
  headerPrep.components = [
    {
      component: defineAsyncComponent(() => import('~/components/app/kfr/_common/btn-history.vue')),
      props: {  }
    },
  ];
}

  
const defaultDate = {
  start: new CalendarDate(2025, 1, 20),
  end: new CalendarDate(2025, 1, 20).add({ days: 20 }),
}
const historyDateValue = ref(defaultDate) as Ref<DateRange>
// #endregion

// #region Lifecycle Hooks
onMounted(() => {
  getPatientSummary()

  const isInTherapy = false // TODO: determine if patient is in therapy
  handleIsPatientInTherapy(isInTherapy)
})
// #endregion

// #region Functions
function handleIsInAssesmentPeriood(value: boolean) {
  if (value) {
    isInOrBeyondAssessmentPeriod.value = true
  } else {
    isInOrBeyondAssessmentPeriod.value = false
  }
}
function handleIsPatientInTherapy(value: boolean) {
  if (value) {
    isPatientInTherapy.value = true
  } else {
    isPatientInTherapy.value = false
  }
}

async function handleOpenHistory() {
  isHistoryDialogOpen.value = true
}
async function getPatientSummary() {
  try {
    summaryLoading.value = true
    await new Promise((resolve) => setTimeout(resolve, 500))
  } catch (error) {
    console.error('Error fetching patient summary:', error)
  } finally {
    summaryLoading.value = false
  }
}

function toggleHistoryDialog() {
  isHistoryDialogOpen.value = !isHistoryDialogOpen.value
}

function handleVerify() {
  isVerifyDialogOpen.value = true
}

async function handleConfirmVerify() {
  const inputData: any = await composeFormData()
  const response = await handleActionSave(
    inputData,
    () => { },
    () => { },
    toast,
  )

  const data = (response?.body?.data ?? null)
  if (!data) return
  isVerifyDialogOpen.value = false
}

async function composeFormData(): Promise<any> {
  const [input,] = await Promise.all([
    inputForm.value?.validate(),
  ])

  const results = [input]
  const allValid = results.every((r) => r?.valid)

  // exit, if form errors happend during validation
  if (!allValid) return Promise.reject('Form validation failed')

  const formData = input?.values
  // formData.encounter_id = encounterId

  return new Promise((resolve) => resolve(formData))
}

async function handleConfirmValidate() {  
    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 handleCancelValidate() {
  // Reset record state when cancelled
  recId.value = 0
  recAction.value = ''
  recItem.value = null
}

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

// #region Utilities & event handlers
async function handleActionClick(eventType: string) {
  if (eventType === 'submit') {
    handleConfirmVerify()
  }

  if (eventType === 'back') {
    isVerifyDialogOpen.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:
      // if(pagePermission.canUpdate) { 
      navigateTo({
        name: 'rehab-encounter-id-kfr-kfr_id-edit',
        params: {
          kfr_id: kfrId
        }
      })
      // } else {
      //   unauthorizedToast()
      // }
      break
    case ActionEvents.showVerify:
      // if(pagePermission.canUpdate) { 
      handleVerify()
      // } else {
      //   unauthorizedToast()
      // }
      break
    case ActionEvents.showValidate:
      // if(pagePermission.canUpdate) {        
      isValidateDialogOpen.value = true
      // } else {
      //   unauthorizedToast()
      // }
      break
    case ActionEvents.showPrint:
      isDocPreviewDialogOpen.value = true
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})
// #endregion
</script>

<template>
  <Header :prep="{ ...headerPrep }" />

  <AppKfrCommonBannerPatientInTherapy v-if="isInOrBeyondAssessmentPeriod" class="mb-5" />

  <AppKfrList :data="dummy" />

  <Dialog v-model:open="isVerifyDialogOpen" title="Verifikasi">
    <AppKfrVerifyDialog ref="inputForm" :schema="VerificationSchema" />
    <div class="flex justify-end">
      <Action v-show="isCaptchaValid" :enable-draft="false" @click="handleActionClick" />
    </div>
  </Dialog>

  <Confirmation
    v-model:open="isValidateDialogOpen"
    title="Validasi Data"
    message="Apakah Anda yakin ingin Validasi data ini?"
    confirm-text="Simpan"
    @confirm="handleConfirmValidate"
    @cancel="handleCancelValidate"
  />

  <Dialog v-model:open="isHistoryDialogOpen" title="History" size="full">
    <AppKfrHistoryList
      :data="dummy"
      v-model:date-value="historyDateValue"
      :pagination-meta="paginationMeta"
      @page-change="handlePageChange" />
  </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>
      </div>
    </template>
  </RecordConfirmation>

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