<script setup lang="ts">
import TableAntrian from '@/components/pendaftaran/TableAntrian.vue';
import { getAntrianOperasi } from '~/services/antrean';
import { statusOptions, STATUS } from '~/types/antrean';
import { Icon } from '@iconify/vue';
import ModalPendaftaran from '@/components/pendaftaran/ModalPendaftaran.vue';
import ModalDetailPendaftaran from '@/components/pendaftaran/ModalDetailPendaftaran.vue';

const route = useRoute();
const idKategori = route.params.id as string;
const categoryName = route.query.category as string || 'Kategori';

// State
const search = ref('');
const antreanList = ref<any[]>([]);
const statusFilter = ref<string | null>(STATUS.BELUM);
const loading = ref(false);
const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalItems = ref(0);


// Modal state
const showModal = ref(false);
const showDetailModal = ref(false);
const selectedId = ref<string | number | null>(null);

definePageMeta({
    middleware: 'auth',
    buttonBack: true
});

// Set pageTitle from query parameter
watch(() => route.query.category, (category) => {
    const categoryText = category as string || 'Kategori';
    route.meta.pageTitle = `Antrean Operasi Kategori ${categoryText}`;
}, { immediate: true });

// 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,
            status: statusFilter.value || undefined,
            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 status filter changes
watch(statusFilter, () => {
    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(() => {
    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 handleView = (item: unknown) => {
    const data = item as any;
    selectedId.value = data.id;
    showDetailModal.value = true;
};

const handleEdit = (item: unknown) => {
    console.log('Edit', item);
};

const handleDelete = (item: unknown) => {
    if(confirm('Apakah Anda yakin ingin menghapus data ini?')) {
        console.log('Delete', item);
    }
};

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

const handleItemsPerPageUpdate = (items: unknown) => {
    itemsPerPage.value = items as number;
};

const handleModalSuccess = () => {
    fetchData(); // Refresh the table after successful submission
};
</script>
<template>
    <v-row>
        <v-col cols="12">
            <v-card elevation="10">
                <v-card-text>
                    <div class="d-flex justify-space-between align-center mb-4">
                        <div class="d-flex align-center w-50 ga-4">
                            <v-text-field v-model="search" placeholder="Search..." variant="outlined" density="compact"
                                hide-details prepend-inner-icon="mdi-magnify" style="max-width: 300px;"></v-text-field>
                            <v-select v-model="statusFilter" :items="statusOptions" item-title="label"
                                item-value="value" variant="outlined" density="compact" hide-details
                                placeholder="Filter Status" style="max-width: 200px;"></v-select>
                        </div>

                        <v-btn color="primary" size="large" elevation="2" @click="showModal = true">
                            <Icon icon="solar:add-circle-bold" height="20" class="mr-2" />
                            Pendaftaran Operasi Baru
                        </v-btn>
                    </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" 
                        @view="handleView"
                        @edit="handleEdit"
                        @delete="handleDelete"
                        @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>

    <!-- Modal Pendaftaran -->
    <ModalPendaftaran 
        v-model="showModal" 
        mode="create"
        :initial-kategori="parseInt(idKategori)"
        @success="handleModalSuccess"
    />

    <!-- Modal Detail Pendaftaran -->
    <ModalDetailPendaftaran 
        v-if="selectedId"
        v-model="showDetailModal" 
        :id="selectedId"
    />
</template>
