<script setup lang="ts">
import type { Ref } from 'vue'

// Components
import type { DataTableLoader } from '~/components/pub/my-ui/data-table/type'
import type { HeaderPrep, RefSearchNav } from '~/components/pub/my-ui/data/types'
import type { PaginationMeta } from '~/components/pub/my-ui/pagination/pagination.type'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
} from '~/components/pub/ui/dropdown-menu'
import AppSepList from '~/components/app/sep/list.vue'
import RangeCalendar from '~/components/pub/ui/range-calendar/RangeCalendar.vue'
import type { DateRange } from 'radix-vue'
import { CalendarDate, getLocalTimeZone } from '@internationalized/date'
import { toast } from "~/components/pub/ui/toast"

// Icons
import { X, Check } from 'lucide-vue-next'

// Types
import type { VclaimSepData } from '~/models/vclaim'

// Libraries
import { getFormatDateId } from '~/lib/date'

// Constants
import { serviceTypes } from '~/lib/constants.vclaim'

// Services
import { getList as geMonitoringVisitList } from '~/services/vclaim-monitoring-visit.service'
import { remove as removeSepData, makeSepDataForRemove } from "~/services/vclaim-sep.service"

const userStore = useUserStore()
const today = new Date()
// DateRange (radix) selection using CalendarDate
const initCalDate = (d: Date) => new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate())
const search = ref('')
const dateSelection = ref({ start: initCalDate(today), end: initCalDate(today) }) as Ref<DateRange>
const dateRange = ref(`${getFormatDateId(today)} - ${getFormatDateId(today)}`)
const serviceType = ref('2')
const serviceTypesList = ref<any[]>([])
const open = ref(false)

const sepData = ref({
  sepNumber: '',
  cardNumber: '',
  patientName: '',
})

function onRowSelected(row: any) {
  if (!row) return
  // map possible property names from API / table rows
  sepData.value.sepNumber = row.letterNumber || ''
  sepData.value.cardNumber = row.cardNumber || ''
  sepData.value.patientName = row.patientName || ''
  recItem.value = row
  recId.value = (row && (row.id || row.recId)) || 0
}

const paginationMeta = reactive<PaginationMeta>({
  recordCount: 0,
  page: 1,
  pageSize: 10,
  totalPage: 5,
  hasNext: false,
  hasPrev: false,
})

function handlePageChange(page: number) {
  console.log('pageChange', page)
}

const data = ref<VclaimSepData[]>([])

const refSearchNav: RefSearchNav = {
  onClick: () => {
    // open filter modal
  },
  onInput: (_val: string) => {
    // filter patient list
  },
  onClear: () => {
    // clear url param
  },
}

const isLoading = reactive<DataTableLoader>({
  isTableLoading: false,
})

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

const headerPrep: HeaderPrep = {
  title: 'Daftar SEP Prosedur',
  icon: 'i-lucide-panel-bottom',
  addNav: {
    label: 'Tambah',
    onClick: () => {
      navigateTo('/integration/bpjs/sep/add')
    },
  },
}

function getDateFilter() {
  let dateFilter = '';
  const isTimeLocal = true
  const dateFirst = dateSelection.value && dateSelection.value.start ? dateSelection.value.start.toDate(getLocalTimeZone()) : new Date()
  if (isTimeLocal && dateSelection.value && dateSelection.value.end) {
    const { year, month, day } = dateSelection.value.end
    dateFilter = `${year}-${month}-${day}`
  } else {
    dateFilter = dateFirst.toISOString().substring(0, 10)
  }
  return dateFilter
}

async function getMonitoringVisitMappers() {
  isLoading.dataListLoading = true
  data.value = []
  const dateFilter = getDateFilter()
  const result = await geMonitoringVisitList({
    date: dateFilter || '',
    serviceType: serviceType.value,
  })

  if (result && result.success && result.body) {
    const visitsRaw = result.body?.response?.sep || []

    if (!visitsRaw) {
      isLoading.dataListLoading = false
      return
    }

    visitsRaw.forEach((result: any) => {
      // Format pelayanan: "R.Inap" -> "Rawat Inap", "1" -> "Rawat Jalan", dll
      let serviceType = result.jnsPelayanan || '-'
      if (serviceType === 'R.Inap') {
        serviceType = 'Rawat Inap'
      } else if (serviceType === '1' || serviceType === 'R.Jalan') {
        serviceType = 'Rawat Jalan'
      }

      data.value.push({
        letterDate: result.tglSep || '-',
        letterNumber: result.noSep || '-',
        serviceType: serviceType,
        flow: '-',
        medicalRecordNumber: '-',
        patientName: result.nama || '-',
        cardNumber: result.noKartu || '-',
        controlLetterNumber: result.noRujukan || '-',
        controlLetterDate: result.tglPlgSep || '-',
        clinicDestination: result.poli || '-',
        attendingDoctor: '-',
        diagnosis: result.diagnosa || '-',
        careClass: result.kelasRawat || '-',
      })
    })
  }

  isLoading.dataListLoading = false
}

async function getSepList() {
  await getMonitoringVisitMappers()
}

function exportCsv() {
  console.log('Ekspor CSV dipilih')
  // tambahkan logic untuk generate CSV
}

function exportExcel() {
  console.log('Ekspor Excel dipilih')
  // tambahkan logic untuk generate Excel
}

async function handleRemove() {
  console.log('Data dihapus:', sepData)
  const result = await removeSepData(makeSepDataForRemove({ ...sepData.value, userName: userStore.user?.user_name }))
  if (result && result.success && result.body) {
    await getSepList()
    toast({ title: 'Berhasil', description: 'Data berhasil dihapus', variant: 'default' })
  } else {
    toast({ title: 'Gagal', description: 'Gagal menghapus data', variant: 'destructive' })
  }
  open.value = false
}

watch(
  () => recAction.value,
  () => {
    if (recAction.value === 'showConfirmDel') {
      open.value = true
    }
  },
)

// When date selection changes, update display and re-fetch
watch(
  () => dateSelection.value,
  (val) => {
    if (!val) return
    const startCal = val.start
    const endCal = val.end
    const s = startCal ? startCal.toDate(getLocalTimeZone()) : today
    const e = endCal ? endCal.toDate(getLocalTimeZone()) : today
    dateRange.value = `${getFormatDateId(s)} - ${getFormatDateId(e)}`
    getSepList()
  },
  { deep: true },
)

// Refetch when serviceType filter changes
watch(
  () => serviceType.value,
  () => {
    getSepList()
  },
)

onMounted(() => {
  serviceTypesList.value = Object.keys(serviceTypes).map((item) => ({
    value: item.toString(),
    label: serviceTypes[item],
  })) as any
  getSepList()
})

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)
</script>

<template>
  <div class="p-4">
    <Header :prep="{ ...headerPrep }" />
    <!-- Filter Bar -->
    <div class="my-2 flex flex-wrap items-center gap-2">
      <!-- Search -->
      <Input v-model="search" placeholder="Cari No. SEP / No. Kartu BPJS..." class="w-72" />

      <!-- Filter -->
      <div class="w-72">
        <Select id="serviceType" icon-name="i-lucide-chevron-down" v-model="serviceType" :items="serviceTypesList"
          placeholder="Pilih Pelayanan" />
      </div>

      <!-- Date Range -->
      <Popover>
        <PopoverTrigger as-child>
          <Button variant="outline" class="h-[40px] w-72 border-gray-400 bg-white text-right font-normal">
            {{ dateRange }}
            <Icon name="i-lucide-calendar" class="h-5 w-5" />
          </Button>
        </PopoverTrigger>
        <PopoverContent class="p-2">
          <RangeCalendar v-model="dateSelection" />
        </PopoverContent>
      </Popover>

      <!-- Export -->
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <Button variant="outline"
            class="ml-auto h-[40px] w-[120px] rounded-md border-green-600 text-green-600 hover:bg-green-50">
            <Icon name="i-lucide-download" class="h-5 w-5" />
            Ekspor
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent class="w-40">
          <DropdownMenuItem @click="exportCsv">Ekspor CSV</DropdownMenuItem>
          <DropdownMenuItem @click="exportExcel">Ekspor Excel</DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>

    <div class="mt-4">
      <AppSepList v-if="!isLoading.dataListLoading" :data="data" @update:modelValue="onRowSelected" />
    </div>

    <!-- Pagination -->
    <template v-if="paginationMeta">
      <div v-if="paginationMeta.totalPage > 1">
        <PubMyUiPagination :pagination-meta="paginationMeta" @page-change="handlePageChange" />
      </div>
    </template>

    <!-- Trigger button -->
    <Dialog v-model:open="open">
      <DialogTrigger as-child></DialogTrigger>
      <DialogContent class="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Hapus SEP</DialogTitle>
        </DialogHeader>
        <DialogDescription class="text-gray-700">Apakah anda yakin ingin menghapus SEP dengan data:</DialogDescription>
        <div class="mt-4 space-y-2 text-sm">
          <p><strong>No. SEP:</strong> {{ sepData.sepNumber }}</p>
          <p><strong>No. Kartu BPJS:</strong> {{ sepData.cardNumber }}</p>
          <p><strong>Nama Pasien:</strong> {{ sepData.patientName }}</p>
        </div>
        <DialogFooter class="mt-6 flex justify-end gap-3">
          <Button variant="outline" class="border-green-600 text-green-600 hover:bg-green-50" @click="handleRemove">
            <X class="mr-1 h-4 w-4" />
            Tidak
          </Button>
          <Button variant="destructive" class="bg-red-600 hover:bg-red-700" @click="handleRemove">
            <Check class="mr-1 h-4 w-4" />
            Ya
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </div>
</template>
