<script setup lang="ts">
import { ref, watch } from 'vue';
import { Head, useForm, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Truck, Phone, Mail, MapPin, User, Edit2, Trash2, Plus, AlertCircle, X } from 'lucide-vue-next';

interface SupplierData {
    id: number;
    name: string;
    phone: string | null;
    email: string | null;
    address: string | null;
    contact_person: string | null;
    created_at: string;
}

interface PaginatedSuppliers {
    data: SupplierData[];
    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<{
    suppliers: PaginatedSuppliers;
    filters: {
        search?: string;
    };
}>();

const search = ref(props.filters.search || '');

// Debounce search
let timeoutId: ReturnType<typeof setTimeout> | null = null;
watch(search, () => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
        router.get(
            route('suppliers.index'),
            { search: search.value },
            { preserveState: true, replace: true }
        );
    }, 400);
});

// Modal state
const isFormModalOpen = ref(false);
const isDeleteModalOpen = ref(false);
const editingSupplier = ref<SupplierData | null>(null);
const supplierToDelete = ref<SupplierData | null>(null);

// Form config
const form = useForm({
    name: '',
    phone: '',
    email: '',
    address: '',
    contact_person: '',
});

const openCreateModal = () => {
    editingSupplier.value = null;
    form.clearErrors();
    form.reset();
    isFormModalOpen.value = true;
};

const openEditModal = (supplier: SupplierData) => {
    editingSupplier.value = supplier;
    form.clearErrors();
    form.name = supplier.name;
    form.phone = supplier.phone || '';
    form.email = supplier.email || '';
    form.address = supplier.address || '';
    form.contact_person = supplier.contact_person || '';
    isFormModalOpen.value = true;
};

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

const confirmDelete = (supplier: SupplierData) => {
    supplierToDelete.value = supplier;
    isDeleteModalOpen.value = true;
};

const submitDelete = () => {
    if (supplierToDelete.value) {
        router.delete(route('suppliers.destroy', supplierToDelete.value.id), {
            onSuccess: () => {
                isDeleteModalOpen.value = false;
                supplierToDelete.value = null;
            },
        });
    }
};
</script>

<template>
    <Head title="Supplier Manager - CafePOS" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">Supplier Manager</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Manage raw ingredient partners and coffee bean suppliers.
                    </p>
                </div>
                
                <button
                    @click="openCreateModal"
                    class="px-4 py-2.5 bg-red-600 hover:bg-red-500 text-white rounded-xl text-xs font-bold transition-all duration-200 flex items-center gap-2 shadow-sm hover:shadow hover:-translate-y-0.5 self-start sm:self-auto cursor-pointer border-0"
                >
                    <Plus class="h-4 w-4" />
                    <span>Add Supplier</span>
                </button>
            </div>

            <!-- Main controls & list -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm space-y-4">
                <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 px-5 pt-5">
                    <!-- Search bar -->
                    <div class="relative w-full sm:max-w-md">
                        <Search class="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                        <input
                            v-model="search"
                            type="text"
                            placeholder="Search suppliers by name, email, or contact person..."
                            class="w-full pl-10 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100 placeholder-slate-400"
                        />
                    </div>
                    
                    <div class="text-xs font-semibold text-slate-500 dark:text-slate-400">
                        Total: {{ suppliers.total }} Suppliers
                    </div>
                </div>

                <!-- Supplier Table -->
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left text-xs">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 font-bold text-slate-500 dark:text-slate-400">
                                <th class="p-3">Supplier Name</th>
                                <th class="p-3">Contact Person</th>
                                <th class="p-3">Phone</th>
                                <th class="p-3">Email</th>
                                <th class="p-3">Address</th>
                                <th class="p-3 text-right pr-4">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
                            <tr v-if="suppliers.data.length === 0">
                                <td colspan="6" class="p-8 text-center text-slate-400 italic">
                                    No suppliers registered. Click "Add Supplier" to register one.
                                </td>
                            </tr>
                            <tr 
                                v-for="sp in suppliers.data" 
                                :key="sp.id"
                                class="hover:bg-slate-50/30 dark:hover:bg-slate-900/20 transition-colors text-slate-800 dark:text-slate-200 font-medium"
                            >
                                <td class="p-3 font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                                    <Truck class="h-4 w-4 text-slate-400 flex-shrink-0" />
                                    <span>{{ sp.name }}</span>
                                </td>
                                <td class="p-3">
                                    <div class="flex items-center gap-1.5" v-if="sp.contact_person">
                                        <User class="h-3.5 w-3.5 text-slate-400" />
                                        <span>{{ sp.contact_person }}</span>
                                    </div>
                                    <span v-else class="text-slate-400 italic">-</span>
                                </td>
                                <td class="p-3">
                                    <div class="flex items-center gap-1.5" v-if="sp.phone">
                                        <Phone class="h-3.5 w-3.5 text-slate-400" />
                                        <span>{{ sp.phone }}</span>
                                    </div>
                                    <span v-else class="text-slate-400 italic">-</span>
                                </td>
                                <td class="p-3">
                                    <div class="flex items-center gap-1.5" v-if="sp.email">
                                        <Mail class="h-3.5 w-3.5 text-slate-400" />
                                        <span>{{ sp.email }}</span>
                                    </div>
                                    <span v-else class="text-slate-400 italic">-</span>
                                </td>
                                <td class="p-3 max-w-xs truncate">
                                    <div class="flex items-center gap-1.5" v-if="sp.address">
                                        <MapPin class="h-3.5 w-3.5 text-slate-400 flex-shrink-0" />
                                        <span class="truncate">{{ sp.address }}</span>
                                    </div>
                                    <span v-else class="text-slate-400 italic">-</span>
                                </td>
                                <td class="p-3 text-right pr-4">
                                    <div class="flex items-center justify-end gap-1.5">
                                        <button
                                            @click="openEditModal(sp)"
                                            class="p-1.5 rounded-lg text-slate-400 hover:text-slate-650 dark:hover:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors cursor-pointer border-0 bg-transparent"
                                            title="Edit Supplier"
                                        >
                                            <Edit2 class="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            @click="confirmDelete(sp)"
                                            class="p-1.5 rounded-lg text-slate-400 hover:text-rose-600 hover:bg-rose-50/20 transition-colors cursor-pointer border-0 bg-transparent"
                                            title="Delete Supplier"
                                        >
                                            <Trash2 class="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination footer -->
                <div v-if="suppliers.last_page > 1" class="flex flex-wrap items-center justify-between gap-4 pt-4 border-t border-slate-200 dark:border-slate-800">
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-semibold">
                        Page {{ suppliers.current_page }} of {{ suppliers.last_page }}
                    </div>
                    
                    <div class="flex items-center gap-1">
                        <Link
                            v-for="(link, lIdx) in suppliers.links"
                            :key="lIdx"
                            v-show="link.url || lIdx === 0 || lIdx === suppliers.links.length - 1"
                            :href="link.url || '#'"
                            :class="[
                                'px-3 py-1.5 text-xs font-semibold rounded-lg border transition-all cursor-pointer select-none',
                                link.active 
                                    ? 'bg-red-50 dark:bg-red-95/10 border-red-500 text-red-650 dark:text-red-400' 
                                    : 'border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-900',
                                !link.url ? 'opacity-40 cursor-not-allowed' : ''
                            ]"
                            v-html="link.label"
                        />
                    </div>
                </div>
            </div>
        </div>

        <!-- Add / Edit Modal Form -->
        <div v-if="isFormModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <form @submit.prevent="submitForm" class="w-full max-w-lg bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 flex flex-col max-h-[90vh]">
                <!-- Modal Title -->
                <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between flex-shrink-0 bg-slate-50/50 dark:bg-slate-900/10">
                    <h3 class="text-sm font-bold text-slate-900 dark:text-slate-100">
                        {{ editingSupplier ? 'Edit Supplier' : 'Register New Supplier' }}
                    </h3>
                    <button type="button" @click="isFormModalOpen = false" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 cursor-pointer border-0 bg-transparent">
                        <X class="h-4 w-4" />
                    </button>
                </div>

                <!-- Modal Body (Scrollable) -->
                <div class="flex-1 overflow-y-auto p-6 space-y-4">
                    <!-- Supplier Name -->
                    <div class="space-y-1">
                        <label for="name" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Supplier Name <span class="text-rose-500">*</span></label>
                        <input
                            id="name"
                            v-model="form.name"
                            type="text"
                            required
                            class="w-full px-3.5 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                            placeholder="e.g. Sumatra Coffee Beans Corp"
                        />
                        <p v-if="form.errors.name" class="text-xs text-rose-600 mt-1">{{ form.errors.name }}</p>
                    </div>

                    <!-- Contact Person Name -->
                    <div class="space-y-1">
                        <label for="contact_person" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Contact Person</label>
                        <input
                            id="contact_person"
                            v-model="form.contact_person"
                            type="text"
                            class="w-full px-3.5 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                            placeholder="e.g. John Doe"
                        />
                        <p v-if="form.errors.contact_person" class="text-xs text-rose-600 mt-1">{{ form.errors.contact_person }}</p>
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <!-- Phone -->
                        <div class="space-y-1">
                            <label for="phone" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Phone Number</label>
                            <input
                                id="phone"
                                v-model="form.phone"
                                type="text"
                                class="w-full px-3.5 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                                placeholder="e.g. 08123456789"
                            />
                            <p v-if="form.errors.phone" class="text-xs text-rose-600 mt-1">{{ form.errors.phone }}</p>
                        </div>

                        <!-- Email -->
                        <div class="space-y-1">
                            <label for="email" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Email Address</label>
                            <input
                                id="email"
                                v-model="form.email"
                                type="email"
                                class="w-full px-3.5 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                                placeholder="e.g. sales@sumatracoffee.com"
                            />
                            <p v-if="form.errors.email" class="text-xs text-rose-600 mt-1">{{ form.errors.email }}</p>
                        </div>
                    </div>

                    <!-- Address -->
                    <div class="space-y-1">
                        <label for="address" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Office Address</label>
                        <textarea
                            id="address"
                            v-model="form.address"
                            rows="3"
                            class="w-full px-3.5 py-2 border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent text-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 focus:border-red-500 transition-all text-slate-900 dark:text-slate-100"
                            placeholder="Full office address details..."
                        ></textarea>
                        <p v-if="form.errors.address" class="text-xs text-rose-600 mt-1">{{ form.errors.address }}</p>
                    </div>
                </div>

                <!-- Action buttons -->
                <div class="flex items-center justify-end gap-3 p-6 border-t border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/10 flex-shrink-0">
                    <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-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer bg-transparent"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="px-4 py-2 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm font-semibold shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500/20 disabled:opacity-50 transition-all cursor-pointer border-0"
                    >
                        {{ form.processing ? 'Saving...' : 'Save' }}
                    </button>
                </div>
            </form>
        </div>

        <!-- Delete Confirmation Modal -->
        <div v-if="isDeleteModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-sm">
            <div class="w-full max-w-md bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl p-6 animate-in zoom-in-95 duration-200 space-y-6">
                <div class="flex items-center gap-3 text-rose-600 dark:text-rose-400">
                    <AlertCircle class="h-6 w-6 flex-shrink-0" />
                    <h3 class="text-lg font-bold">Delete Supplier</h3>
                </div>
                
                <p class="text-sm text-slate-550 dark:text-slate-400 font-medium">
                    Are you sure you want to delete supplier <strong class="text-slate-800 dark:text-slate-200">{{ supplierToDelete?.name }}</strong>? This will decouple it from historical stock records, but the stock quantities will remain unchanged.
                </p>

                <div class="flex items-center justify-end gap-3">
                    <button
                        @click="isDeleteModalOpen = false"
                        class="px-4 py-2 border border-slate-200 dark:border-slate-800 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer bg-transparent"
                    >
                        Cancel
                    </button>
                    <button
                        @click="submitDelete"
                        class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-sm font-semibold transition-all cursor-pointer border-0"
                    >
                        Delete Supplier
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
