<script setup lang="ts">
// Composables
import { usePaginatedList } from '~/composables/usePaginatedList'

// Pubs component
import { toast } from '~/components/pub/ui/toast'
import { type HeaderPrep } from '~/components/pub/my-ui/data/types'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isRecordConfirmationOpen,
  handleActionRemove,
  handleActionSave,
} from '~/handlers/prescription.handler'

// Services
import { getList, getDetail } from '~/services/prescription.service'
import FlatList from '~/components/app/prescription/flat-list.vue'
import Grouped from '~/components/app/prescription/grouped-list.vue'
import type { Prescription } from '~/models/prescription'
import { submit } from '~/services/prescription.service'
import type { ToastFn } from '~/handlers/_handler'

const route = useRoute()
const { setQueryParams } = useQueryParam()

const title = ref('')
const isSubmitConfirmationOpen = ref(false)

const plainEid = route.params.id
const encounter_id = (plainEid && typeof plainEid == 'string') ? parseInt(plainEid) : 0

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  fetchData: getMyList,
} = usePaginatedList<Prescription>({
  fetchFn: async (params: any) => {
    const result = await getList({
      'encounter-id': encounter_id,
      includes: 'doctor,doctor-employee,doctor-employee-person,items,items-medicine,items-medicine-medicineForm',
      search: params.search,
      page: params.page,
      'page-number': params['page-number'] || 0,
      'page-size': params['page-size'] || 10,
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'prescription'
})

function updateProvidedVal(val: boolean) {
  flatMode.value = val
}
const flatMode = ref(false)
const flatModeLabel = ref('Mode Flat: Tidak')
provide('flatMode', { flatMode, updateProvidedVal })
watch(flatMode, (newVal) => {
  flatModeLabel.value = newVal ? 'Mode Flat: Ya' : 'Mode Flat: Tidak'
})

const vFn = () => {} // Void function
const headerPrep: HeaderPrep = {
  title: 'Order Obat',
  icon: 'i-lucide-box',
  components: [
    {
      component: defineAsyncComponent(() => import('~/components/pub/my-ui/toggle/provided-toggle.vue')),
      props: { variant: 'outline', label: flatModeLabel, providedKey: 'flatMode' }
    },
  ],
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (value: string) => {
      searchInput.value = value
    },
    onClick: () => {},
    onClear: () => {},
  },
  addNav: {
    label: 'Tambah',
    icon: 'i-lucide-plus',
    onClick: async () => {
      recItem.value = null
      recId.value = 0
      isReadonly.value = false
      const saveResp = await handleActionSave({ encounter_id }, vFn, vFn, vFn)
      if (saveResp.success) {
        setQueryParams({
          'mode': 'entry',
          'id': saveResp.body?.data?.id.toString()
        })
      }
    },
  },
}

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)

function confirmCancel(data: Prescription) {
  recId.value = data.id
  recItem.value = data
  isRecordConfirmationOpen.value = true
}

function goToEdit(data: Prescription) {
  setQueryParams({
    'mode': 'entry',
    'id': data.id.toString()
  })
  recItem.value = data
}

function confirmSubmit(data: Prescription) {
  recId.value = data.id
  recItem.value = data
  isSubmitConfirmationOpen.value = true
}

async function handleActionSubmit(id: number, refresh: () => void, toast: ToastFn) {
  const result = await submit(id)
  if (result.success) {
    toast({ title: 'Berhasil', description: 'Resep telah di ajukan', variant: 'default' })
    setTimeout(refresh, 300)
  } else {
    toast({ title: 'Gagal', description: 'Gagal menjalankan perintah', variant: 'destructive' })
  }
}
</script>

<template>
  <Header :prep="{ ...headerPrep }" />
  <template v-if="!flatMode">
    <Grouped 
      v-if="!isLoading.dataListLoading"
      :data="data"
      :pagination-meta="paginationMeta"
      @cancel="confirmCancel"
      @edit="goToEdit"
      @submit="confirmSubmit"
    />
  </template>
  <template v-else>
    <FlatList
      v-if="!isLoading.dataListLoading"
      :data="data"
      :pagination-meta="paginationMeta"
      @cancel="confirmCancel"
      @edit="goToEdit"
      @submit="confirmSubmit"
    />
  </template>

  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recId, getMyList, toast)"
    @cancel=""
  >
    <div class="flex mb-2">
      <div class="w-20">Tanggal</div>
      <div class="w-4">:</div>
      <div class="">{{ recItem.createdAt.substring(0, 10) }}</div>
    </div>
    <div class="flex">
      <div class="w-20">DPJP</div>
      <div class="w-4">:</div>
      <div class="">{{ recItem.doctor?.employee?.person?.name }}</div>
    </div>
  </RecordConfirmation>

  <RecordConfirmation
    v-model:open="isSubmitConfirmationOpen"
    action="delete"
    customTitle="Ajukan Resep"
    customMessage="Proses akan mengajukan resep ini untuk diproses lebih lanjut. Lanjutkan?"
    customConfirmText="Ajukan"
    :record="recItem"
    @confirm="() => handleActionSubmit(recId, getMyList, toast)"
    @cancel=""
  >
    <div class="flex mb-2">
      <div class="w-20">Tanggal</div>
      <div class="w-4">:</div>
      <div class="">{{ recItem.createdAt.substring(0, 10) }}</div>
    </div>
    <div class="flex">
      <div class="w-20">DPJP</div>
      <div class="w-4">:</div>
      <div class="">{{ recItem.doctor?.employee?.person?.name }}</div>
    </div>
  </RecordConfirmation>
</template>
