<script setup lang="ts">
import BaseBreadcrumb from '@/components/shared/BaseBreadcrumb.vue';
import TableAntrian from '@/components/pendaftaran/TableAntrian.vue';
import { getAntrianOperasi } from '~/services/antrean';
import api from '~/services/api';
import type { KategoriOperasi } from '~/types/antrean';

const route = useRoute();
const idKategori = route.params.id as string;

// State
const kategoriInfo = ref<KategoriOperasi | null>(null);
const isLoadingKategori = ref(false);
const search = ref('');
const antreanList = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalItems = ref(0);

// Fetch kategori info
const fetchKategoriInfo = async () => {
    try {
        isLoadingKategori.value = true;
        const response = await api.get('/kategori');
        
        if (response.data.success && response.data.data) {
            kategoriInfo.value = response.data.data.find((k: KategoriOperasi) => k.id === parseInt(idKategori));
        }
    } catch (error) {
        console.error('Error fetching kategori info:', error);
    } finally {
        isLoadingKategori.value = false;
    }
};

definePageMeta({
  middleware: 'auth'
});

const page = computed(() => ({
    title: kategoriInfo.value ? `List Antrian Kategori ${kategoriInfo.value.kategori}` : 'List Antrian Kategori'
}));

const breadcrumbs = computed(() => [
    {
        text: 'Antrean',
        disabled: false,
        href: '/antrean'
    },
    {
        text: 'List Kategori',
        disabled: false,
        href: '/antrean/list-kategori'
    },
    {
        text: kategoriInfo.value ? kategoriInfo.value.kategori : 'Kategori',
        disabled: true,
        href: '#'
    }
]);

// Fetch data from API
const fetchData = async () => {
    loading.value = true;
    try {
        const offset = (currentPage.value - 1) * itemsPerPage.value;
        const response = await getAntrianOperasi({
            type: 'kategori',
            limit: itemsPerPage.value,
            offset: offset,
            search: search.value || undefined,
            type_id: idKategori
        });
        
        if (response.success) {
            antreanList.value = response.data;
            totalItems.value = response.Paginate.Total;
        }
    } catch (error) {
        console.error('Error fetching antrian operasi:', error);
    } finally {
        loading.value = false;
    }
};

// Watch for page changes
watch(currentPage, () => {
    fetchData();
});

watch(itemsPerPage, () => {
    currentPage.value = 1;
    fetchData();
});

// Watch for search with debounce
let searchTimeout: NodeJS.Timeout | null = null;
watch(search, () => {
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }
    searchTimeout = setTimeout(() => {
        currentPage.value = 1;
        fetchData();
    }, 500);
});

// Initial fetch
onMounted(() => {
    fetchKategoriInfo();
    fetchData();
});

const headers = [
    { title: 'Nomor', key: 'NoUrutKategori', width: '50px', align: 'center' as const, sortable: false },
    { title: 'Nomor Spesialis', key: 'NoUrutSpesialis', width: '100px', align: 'center' as const, sortable: false },
    { title: 'Nomor Sub Spesialis', key: 'NoUrutSubSpesialis', width: '140px', align: 'center' as const, sortable: false },
    { title: 'Tanggal Daftar', key: 'TglDaftar', sortable: false, width: '150px' },
    { title: 'No Rekam Medis', key: 'NoRekamMedis', sortable: false, width: '180px' },
    { title: 'Nama Pasien', key: 'NamaPasien', sortable: false },
    { title: 'Jenis kelamin', key: 'JenisKelamin', sortable: false },
    { title: 'Status', key: 'StatusOperasi', sortable: false, width: '150px' },
    { title: 'Actions', key: 'actions', sortable: false, width: '120px' }

];

const actions = [
    { icon: 'mdi-eye', color: 'info', tooltip: 'View', event: 'view' },
    { icon: 'mdi-pencil', color: 'primary', tooltip: 'Edit', event: 'edit' },
    { icon: 'mdi-delete', color: 'error', tooltip: 'Delete', event: 'delete' }
];

const handlePageUpdate = (page: unknown) => {
    currentPage.value = page as number;
};

const handleItemsPerPageUpdate = (items: unknown) => {
    itemsPerPage.value = items as number;
};
</script>
<template>
    <v-row>
        <v-col cols="12">
            <BaseBreadcrumb :title="page.title" :button-back="true" :breadcrumbs="breadcrumbs"></BaseBreadcrumb>
        </v-col>
        <v-col cols="12">
            <v-card elevation="10">
                <v-card-text>
                    <div class="d-flex justify-space-between align-center mb-4">
                        <v-text-field 
                            v-model="search" 
                            placeholder="Search..." 
                            variant="outlined" 
                            density="comfortable"
                            hide-details 
                            prepend-inner-icon="mdi-magnify" 
                            style="max-width: 400px;"
                        ></v-text-field>
                    </div>
                    
                    <TableAntrian
                        :headers="headers"
                        :actions="actions"
                        :items="antreanList"
                        :server-side="true"
                        :total-items="totalItems"
                        :current-page="currentPage"
                        :items-per-page="itemsPerPage"
                        :loading="loading"
                        min-width="1500px"
                        @update:page="handlePageUpdate"
                        @update:itemsPerPage="handleItemsPerPageUpdate"
                    >
                        <template #item.TglDaftar="{ item }">
                            {{ new Date(item.TglDaftar).toLocaleDateString('id-ID', { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric' }) }}
                        </template>
                    </TableAntrian>
                </v-card-text>
            </v-card>
        </v-col>
    </v-row>
</template>
