<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Calendar, Plus, Edit2, Trash2, Clock, Users, Grid, Store, Check, X } from 'lucide-vue-next';

interface Customer {
    id: number;
    name: string;
}

interface Table {
    id: number;
    number: string;
    outlet_id: number;
}

interface Outlet {
    id: number;
    name: string;
}

interface ReservationData {
    id: number;
    customer_id: number;
    table_id: number;
    outlet_id: number;
    reservation_date: string;
    reservation_time: string;
    status: 'pending' | 'confirmed' | 'cancelled';
    customer?: Customer;
    table?: Table;
    outlet?: Outlet;
    created_at: string;
}

interface PaginatedReservations {
    data: ReservationData[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
}

const props = defineProps<{
    reservations: PaginatedReservations;
    outlets: Outlet[];
    customers: Customer[];
    tables: Table[];
    filters: {
        outlet_id?: string;
    };
}>();

const selectedOutletId = ref(props.filters.outlet_id || (props.outlets[0] ? String(props.outlets[0].id) : ''));

watch(selectedOutletId, (newVal) => {
    router.get(
        route('reservations.index'),
        { outlet_id: newVal },
        { preserveState: true, replace: true }
    );
});

// Modal state
const isFormModalOpen = ref(false);
const editingReservation = ref<ReservationData | null>(null);

// Form config
const form = useForm({
    customer_id: '',
    table_id: '',
    outlet_id: selectedOutletId.value ? Number(selectedOutletId.value) : 0,
    reservation_date: '',
    reservation_time: '',
    status: 'pending',
});

// Filter tables by current selected outlet for form
const formFilteredTables = computed(() => {
    return props.tables.filter(t => t.outlet_id === Number(form.outlet_id));
});

const openCreateModal = () => {
    editingReservation.value = null;
    form.clearErrors();
    form.reset();
    form.outlet_id = selectedOutletId.value ? Number(selectedOutletId.value) : 0;
    isFormModalOpen.value = true;
};

const openEditModal = (res: ReservationData) => {
    editingReservation.value = res;
    form.clearErrors();
    form.customer_id = String(res.customer_id);
    form.outlet_id = res.outlet_id;
    form.table_id = String(res.table_id);
    form.reservation_date = res.reservation_date;
    form.reservation_time = res.reservation_time.slice(0, 5); // hh:mm format
    form.status = res.status;
    isFormModalOpen.value = true;
};

const submitForm = () => {
    if (editingReservation.value) {
        form.put(route('reservations.update', editingReservation.value.id), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        form.post(route('reservations.store'), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const deleteReservation = (res: ReservationData) => {
    if (confirm('Apakah Anda yakin ingin menghapus reservasi ini?')) {
        router.delete(route('reservations.destroy', res.id));
    }
};

const getStatusBadge = (status: string) => {
    switch (status) {
        case 'pending': return 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20';
        case 'confirmed': return 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20';
        case 'cancelled': return 'bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/20';
        default: return 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20';
    }
};
</script>

<template>
    <Head title="Reservasi Meja" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50 tracking-tight">
                        Reservasi Meja
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Catat dan kelola pesanan meja dari pelanggan untuk waktu tertentu.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="flex items-center justify-center gap-2 px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-sm font-bold rounded-xl transition-all cursor-pointer shadow-lg shadow-[#8c5a3c]/10"
                >
                    <Plus class="h-4 w-4" />
                    Buat Reservasi
                </button>
            </div>

            <!-- Controls row -->
            <div class="flex flex-wrap items-center justify-between gap-4 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl px-5 py-4 shadow-sm">
                <!-- Outlet selector -->
                <div class="flex items-center gap-3">
                    <Store class="h-5 w-5 text-slate-400" />
                    <span class="text-xs font-bold text-slate-500 uppercase tracking-wide">Cabang Outlet:</span>
                    <select
                        v-model="selectedOutletId"
                        class="h-9 px-3 border border-slate-200 dark:border-slate-700 rounded-lg bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 text-slate-900 dark:text-slate-100 cursor-pointer"
                    >
                        <option v-for="ot in outlets" :key="ot.id" :value="String(ot.id)">{{ ot.name }}</option>
                    </select>
                </div>
            </div>

            <!-- Reservations Table -->
            <div v-if="reservations.data.length > 0" class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Pelanggan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Meja</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Cabang</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Waktu Pemesanan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <tr v-for="res in reservations.data" :key="res.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-2">
                                        <Users class="h-4 w-4 text-[#8c5a3c]" />
                                        <span class="font-extrabold text-xs text-slate-850 dark:text-slate-100">{{ res.customer?.name }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="font-bold text-xs text-slate-700 dark:text-slate-350">{{ res.table?.number }}</span>
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-500">
                                    {{ res.outlet?.name }}
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex flex-col gap-0.5 text-xs text-slate-655 dark:text-slate-300">
                                        <span class="font-semibold flex items-center gap-1.5"><Calendar class="h-3.5 w-3.5 text-slate-400" /> {{ new Date(res.reservation_date).toLocaleDateString('id-ID', { dateStyle: 'medium' }) }}</span>
                                        <span class="text-[10px] text-slate-400 flex items-center gap-1.5"><Clock class="h-3.5 w-3.5 text-slate-400" /> {{ res.reservation_time.slice(0, 5) }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span :class="['px-2.5 py-0.5 border rounded-full text-[9px] font-extrabold uppercase tracking-wider', getStatusBadge(res.status)]">
                                        {{ res.status }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <button
                                            @click="openEditModal(res)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 dark:hover:text-slate-200 rounded-lg cursor-pointer"
                                        >
                                            <Edit2 class="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            @click="deleteReservation(res)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-555 hover:text-rose-600 rounded-lg cursor-pointer"
                                        >
                                            <Trash2 class="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Simple Pagination -->
                <div v-if="reservations.last_page > 1" class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-between gap-4">
                    <span class="text-xs text-slate-500">Total {{ reservations.total }} reservasi</span>
                    <div class="flex items-center gap-2">
                        <Link
                            v-for="link in reservations.links"
                            :key="link.label"
                            :href="link.url || '#'"
                            :class="[
                                'px-3 py-1.5 border rounded-lg text-xs font-semibold cursor-pointer',
                                link.active ? 'bg-[#8c5a3c] text-white border-[#8c5a3c]' : 'border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-700 dark:text-slate-350',
                                !link.url ? 'opacity-50 pointer-events-none' : ''
                            ]"
                            v-html="link.label"
                        />
                    </div>
                </div>
            </div>
            <div v-else class="text-center py-16 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm">
                <Calendar class="h-10 w-10 text-slate-350 dark:text-slate-655 mx-auto mb-3" />
                <h3 class="text-sm font-bold text-slate-800 dark:text-slate-200">Belum ada reservasi</h3>
                <p class="text-xs text-slate-400 mt-1">Gunakan tombol di atas untuk mendaftarkan jadwal booking meja baru.</p>
            </div>

            <!-- Create/Edit Modal -->
            <div v-if="isFormModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
                <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-md overflow-hidden transform transition-all">
                    <!-- Modal Header -->
                    <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                        <h3 class="text-sm font-extrabold text-slate-900 dark:text-slate-100">
                            {{ editingReservation ? 'Edit Detail Booking' : 'Buat Reservasi Meja' }}
                        </h3>
                        <button @click="isFormModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-400 cursor-pointer">
                            <X class="h-4 w-4" />
                        </button>
                    </div>

                    <!-- Modal Body -->
                    <form @submit.prevent="submitForm" class="p-6 space-y-4">
                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Pelanggan</label>
                            <select
                                v-model="form.customer_id"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option value="">Pilih customer...</option>
                                <option v-for="c in customers" :key="c.id" :value="String(c.id)">{{ c.name }}</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Cabang Outlet</label>
                            <select
                                v-model="form.outlet_id"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option v-for="ot in outlets" :key="ot.id" :value="ot.id">{{ ot.name }}</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nomor Meja</label>
                            <select
                                v-model="form.table_id"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option value="">Pilih meja...</option>
                                <option v-for="t in formFilteredTables" :key="t.id" :value="String(t.id)">{{ t.number }}</option>
                            </select>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Tanggal Booking</label>
                                <input
                                    type="date"
                                    v-model="form.reservation_date"
                                    required
                                    class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                                />
                            </div>
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Jam Booking</label>
                                <input
                                    type="time"
                                    v-model="form.reservation_time"
                                    required
                                    class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                                />
                            </div>
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Status Persetujuan</label>
                            <select
                                v-model="form.status"
                                required
                                class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                            >
                                <option value="pending">Pending (Menunggu)</option>
                                <option value="confirmed">Confirmed (Disetujui)</option>
                                <option value="cancelled">Cancelled (Dibatalkan)</option>
                            </select>
                        </div>

                        <!-- Modal Actions Footer -->
                        <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-800">
                            <button
                                type="button"
                                @click="isFormModalOpen = false"
                                class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-350 text-xs font-bold rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer"
                            >
                                Batal
                            </button>
                            <button
                                type="submit"
                                :disabled="form.processing"
                                class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl cursor-pointer disabled:opacity-50"
                            >
                                {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
