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

definePageMeta({
  middleware: 'auth'
});

const page = ref({ title: 'List Antrean Operasi' });
const breadcrumbs = ref([
    {
        text: 'Antrean',
        disabled: false,
        href: '#'
    },
    {
        text: 'List Antrean Operasi',
        disabled: true,
        href: '#'
    }
]);

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

const router = useRouter();

const statusOptions = [
    { value: null, label: 'Semua Status' },
    { value: STATUS.BELUM, label: 'Belum' },
    { value: STATUS.SELESAI, label: 'Selesai' },
    { value: STATUS.TUNDA, label: 'Tunda' },
    { value: STATUS.BATAL, label: 'Batal' }
];

// Fetch data from API
const fetchData = async () => {
    loading.value = true;
    try {
        const offset = (currentPage.value - 1) * itemsPerPage.value;
        const response = await getAntrianOperasi({
            type: 'all',
            limit: itemsPerPage.value,
            offset: offset,
            status: statusFilter.value || undefined,
            search: search.value || undefined
        });
        
        if (response.success) {
            antreanList.value = response.data;
            totalItems.value = response.Paginate.Total;
        }
    } catch (error) {
        console.error('Error fetching antrian operasi:', error);
        showSnackbar('Gagal mengambil data 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); // 500ms debounce
});

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

// Snackbar state
const snackbar = ref(false);
const snackbarMessage = ref('');
const snackbarColor = ref('success');

const showSnackbar = (message: string, color: string = 'success') => {
    snackbarMessage.value = message;
    snackbarColor.value = color;
    snackbar.value = true;
};

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 AntreanOperasi;
    router.push({
        path: '/antrean/pendaftaran',
        query: {
            mode: 'view',
            id: data.id
        }
    });
};

const handleEdit = (item: unknown) => {
    const data = item as AntreanOperasi;
    router.push({
        path: '/antrean/pendaftaran',
        query: {
            mode: 'edit',
            id: data.id
        }
    });
};

const handleDelete = (item: unknown) => {
    if(confirm('Apakah Anda yakin ingin menghapus data ini?')) {
        showSnackbar('Data berhasil dihapus.', 'success');
    }
};

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" :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>
                        
                        <!-- <v-btn
                            color="primary"
                            prepend-icon="mdi-plus"
                            to="/antrean/pendaftaran"
                        >
                            Daftar Antrean Operasi Baru
                        </v-btn> -->
                         <v-select
                                v-model="statusFilter"
                                :items="statusOptions"
                                item-title="label"
                                item-value="value"
                                variant="outlined"
                                density="comfortable"
                                hide-details
                                placeholder="Filter Status"
                                style="max-width: 200px;"
                            ></v-select>
                    </div>

                    <TableAntrian
                        :headers="headers"
                        :items="antreanList"
                        :actions="actions"
                        :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>

    <!-- Snackbar for notifications -->
    <v-snackbar
        v-model="snackbar"
        :color="snackbarColor"
        :timeout="3000"
        location="top"
    >
        {{ snackbarMessage }}
        <template #actions>
            <v-btn
                variant="text"
                @click="snackbar = false"
            >
                Close
            </v-btn>
        </template>
    </v-snackbar>
</template>