<script setup lang="ts">
import { ref, computed } from 'vue'
import { format } from 'date-fns'
import { id as localeID } from 'date-fns/locale'
import { Calendar as CalendarIcon, Filter as FilterIcon, Search } from 'lucide-vue-next'
import { Button } from '~/components/pub/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '~/components/pub/ui/popover'
import Input from '~/components/pub/ui/input/Input.vue'
import RangeCalendar from '~/components/pub/ui/range-calendar/RangeCalendar.vue'
import AppChemotherapyListAdmin from '~/components/app/chemotherapy/list-admin.vue'
import type { PaginationMeta } from '~/components/pub/my-ui/pagination/pagination.type'

// Sample data - replace with actual API call
import { sampleRows, type ChemotherapyData } from '~/components/app/chemotherapy/sample'


const route = useRoute()
const recId = ref(0)
const recAction = ref('')
const recItem = ref<any>(null)

const search = ref('')
const mode = route.params.mode as string || 'admin'
const dateRange = ref<{ from: Date | null; to: Date | null }>({
  from: null,
  to: null,
})

// Format date range for display
const dateRangeDisplay = computed(() => {
  if (dateRange.value.from && dateRange.value.to) {
    return `${format(dateRange.value.from, 'dd MMMM yyyy', { locale: localeID })} - ${format(dateRange.value.to, 'dd MMMM yyyy', { locale: localeID })}`
  }
  return '12 Agustus 2025 - 32 Agustus 2025' // Default display
})

// Filter + search (client-side)
const filtered = computed(() => {
  const q = search.value.trim().toLowerCase()
  return sampleRows.filter((r: ChemotherapyData) => {
    if (q) {
      return r.nama.toLowerCase().includes(q) || r.noRm.toLowerCase().includes(q)
    }
    return true
  })
})

// Pagination meta
const paginationMeta = reactive<PaginationMeta>({
  recordCount: filtered.value.length,
  page: 1,
  pageSize: 10,
  totalPage: Math.ceil(filtered.value.length / 10),
  hasNext: false,
  hasPrev: false,
})

function handlePageChange(page: number) {
  paginationMeta.page = page
  paginationMeta.hasNext = page < paginationMeta.totalPage
  paginationMeta.hasPrev = page > 1
}

function handleFilter() {
  // TODO: Implement filter logic
  console.log('Filter clicked', { search: search.value, dateRange: dateRange.value })
}

// Provide proses handler for action button
function handleProses(rec: any) {
  // Navigate to verification page with record
  navigateTo(`/outpation-action/chemotherapy/verification?id=${rec.id}`)
}

watch([recId, recAction], () => {
  switch (recAction.value) {
    case 'Process':
      navigateTo(`/outpation-action/chemotherapy/${mode}/${recId.value}/verification`)
      break
    case 'Verification':
      break
  }
})

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('proses-handler', handleProses)
</script>

<template>
  <div class="mx-auto max-w-full">
    <!-- Header Section -->
    <div class="border-b p-6">
      <h1 class="text-2xl font-semibold">Administrasi Pasien Rawat Jalan Kemoterapi</h1>
      <p class="mt-1 text-sm text-gray-500">
        Manajemen pendaftaran serta monitoring terapi pasien tindakan rawat jalan
      </p>
    </div>

    <!-- Search and Filter Bar -->
    <div class="flex flex-wrap items-center gap-3 border-b p-4">
      <!-- Search Input -->
      <div class="relative">
        <Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
        <Input
          v-model="search"
          placeholder="Cari Nama /No.RM"
          class="w-64 pl-9"
        />
      </div>

      <!-- Date Range Picker -->
      <Popover>
        <PopoverTrigger as-child>
          <Button
            variant="outline"
            class="h-10 w-72 justify-start border-gray-300 bg-white text-left font-normal"
          >
            <CalendarIcon class="mr-2 h-4 w-4" />
            {{ dateRangeDisplay }}
          </Button>
        </PopoverTrigger>
        <PopoverContent class="w-auto p-0">
          <RangeCalendar />
        </PopoverContent>
      </Popover>

      <!-- Filter Button -->
      <Button
        variant="outline"
        class="ml-auto border-orange-500 bg-orange-50 text-orange-600 hover:bg-orange-100"
        @click="handleFilter"
      >
        <FilterIcon class="mr-2 h-4 w-4" />
        Filter
      </Button>
    </div>

    <!-- Data Table -->
    <div class="overflow-x-auto p-4">
      <AppChemotherapyListAdmin
        :data="filtered"
        :pagination-meta="paginationMeta"
        @page-change="handlePageChange"
      />
    </div>
  </div>
</template>

