<script setup lang="ts">
import { ref, computed } from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { 
    Search, Plus, Pencil, Trash2, X, PlusCircle, Check, HelpCircle, 
    Layers, Coffee, Info, Tag, Sliders
} from 'lucide-vue-next';

interface Ingredient {
    id: number;
    name: string;
    unit: string;
}

interface Product {
    id: number;
    name: string;
    price: number;
    category: string;
}

interface Modifier {
    id: number;
    name: string;
    price: number;
    ingredient_id: number | null;
    usage_qty: number | null;
    is_active: boolean;
    ingredient?: Ingredient | null;
    products?: Product[];
}

interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

interface PaginatedModifiers {
    data: Modifier[];
    links: PaginationLink[];
    current_page: number;
    last_page: number;
    total: number;
}

const props = defineProps<{
    modifiers: PaginatedModifiers;
    ingredients: Ingredient[];
    products: Product[];
    filters: {
        search?: string;
    };
}>();

// Search and filtering
const searchQuery = ref(props.filters.search || '');
const handleSearch = () => {
    router.get(
        route('modifiers.index'),
        { search: searchQuery.value },
        { preserveState: true, replace: true }
    );
};

// Modal state
const isModalOpen = ref(false);
const modalTitle = ref('');
const isEditMode = ref(false);
const editingModifierId = ref<number | null>(null);

// Forms
const form = useForm({
    name: '',
    price: 0,
    ingredient_id: null as number | null,
    usage_qty: null as number | null,
    is_active: true,
    product_ids: [] as number[],
});

// Group products by category for easy selection
const groupedProducts = computed(() => {
    const groups: Record<string, Product[]> = {};
    props.products.forEach(p => {
        if (!groups[p.category]) {
            groups[p.category] = [];
        }
        groups[p.category].push(p);
    });
    return groups;
});

// Open Add Modal
const openAddModal = () => {
    isEditMode.value = false;
    modalTitle.value = 'Tambah Add-on Baru';
    editingModifierId.value = null;
    form.reset();
    form.clearErrors();
    isModalOpen.value = true;
};

// Open Edit Modal
const openEditModal = (modifier: Modifier) => {
    isEditMode.value = true;
    modalTitle.value = 'Ubah Pengaturan Add-on';
    editingModifierId.value = modifier.id;
    form.clearErrors();
    form.name = modifier.name;
    form.price = Number(modifier.price);
    form.ingredient_id = modifier.ingredient_id;
    form.usage_qty = modifier.usage_qty ? Number(modifier.usage_qty) : null;
    form.is_active = modifier.is_active;
    form.product_ids = modifier.products ? modifier.products.map(p => p.id) : [];
    isModalOpen.value = true;
};

// Toggle all products in a category
const toggleCategoryProducts = (category: string, checked: boolean) => {
    const pIds = groupedProducts.value[category].map(p => p.id);
    if (checked) {
        // Add all
        pIds.forEach(id => {
            if (!form.product_ids.includes(id)) {
                form.product_ids.push(id);
            }
        });
    } else {
        // Remove all
        form.product_ids = form.product_ids.filter(id => !pIds.includes(id));
    }
};

const isCategoryFullySelected = (category: string) => {
    const pIds = groupedProducts.value[category].map(p => p.id);
    return pIds.every(id => form.product_ids.includes(id));
};

// Submit form
const handleSubmit = () => {
    if (isEditMode.value && editingModifierId.value) {
        form.put(route('modifiers.update', editingModifierId.value), {
            onSuccess: () => {
                isModalOpen.value = false;
            },
        });
    } else {
        form.post(route('modifiers.store'), {
            onSuccess: () => {
                isModalOpen.value = false;
            },
        });
    }
};

// Delete modifier
const deleteModifier = (modifier: Modifier) => {
    if (confirm(`Apakah Anda yakin ingin menghapus add-on "${modifier.name}"? Relasi ke produk akan dihapus otomatis.`)) {
        router.delete(route('modifiers.destroy', modifier.id));
    }
};
</script>

<template>
    <Head title="Manajemen Add-ons" />

    <AdminLayout>
        <div class="space-y-6 font-sans select-none">
            <!-- Header section -->
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div class="space-y-1">
                    <h1 class="text-xl font-extrabold tracking-tight text-slate-900 dark:text-slate-100 flex items-center gap-2">
                        <Sliders class="h-5 w-5 text-[#8c5a3c]" />
                        <span>Manajemen Add-ons (Modifiers)</span>
                    </h1>
                    <p class="text-xs text-slate-500 dark:text-slate-400">
                        Atur pilihan tambahan makanan/minuman (extra shot, cheese, topping) serta hubungkan ke stok bahan baku secara dinamis.
                    </p>
                </div>

                <button
                    @click="openAddModal"
                    class="px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-xs font-bold rounded-xl flex items-center justify-center gap-1.5 transition-all shadow-md shadow-[#8c5a3c]/10 cursor-pointer"
                >
                    <Plus class="h-4 w-4" />
                    <span>Tambah Add-on</span>
                </button>
            </div>

            <!-- Search and Table Container -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl overflow-hidden shadow-sm">
                <!-- Search bar -->
                <div class="p-4 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between gap-4">
                    <div class="relative flex-1 max-w-sm">
                        <span class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-400">
                            <Search class="h-4 w-4" />
                        </span>
                        <input
                            v-model="searchQuery"
                            @keyup.enter="handleSearch"
                            type="text"
                            placeholder="Cari add-on..."
                            class="w-full pl-9 pr-4 py-2 border border-slate-200 dark:border-slate-800 rounded-xl text-xs bg-slate-50 dark:bg-slate-900/30 focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-800 dark:text-slate-200"
                        />
                    </div>
                </div>

                <!-- Modifiers Table -->
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="bg-slate-50 dark:bg-slate-900/20 text-slate-500 dark:text-slate-400 text-[10px] font-extrabold uppercase tracking-wider border-b border-slate-200 dark:border-slate-800">
                                <th class="p-4">Nama Add-on</th>
                                <th class="p-4">Harga Tambahan</th>
                                <th class="p-4">Stok Pengurang</th>
                                <th class="p-4">Produk Relevan</th>
                                <th class="p-4">Status</th>
                                <th class="p-4 text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-900/50 text-xs font-semibold text-slate-700 dark:text-slate-300">
                            <tr v-if="modifiers.data.length === 0">
                                <td colspan="6" class="p-8 text-center text-slate-400 font-medium">
                                    Tidak ada data add-ons ditemukan.
                                </td>
                            </tr>
                            <tr v-for="mod in modifiers.data" :key="mod.id" class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors">
                                <td class="p-4 font-bold text-slate-900 dark:text-slate-100">
                                    {{ mod.name }}
                                </td>
                                <td class="p-4 text-slate-800 dark:text-slate-200 font-bold">
                                    Rp {{ Number(mod.price).toLocaleString('id-ID') }}
                                </td>
                                <td class="p-4">
                                    <span v-if="mod.ingredient" class="inline-flex items-center gap-1.5 px-2 py-1 bg-amber-50 dark:bg-amber-950/20 border border-amber-200/50 dark:border-amber-900/30 text-amber-700 dark:text-amber-400 rounded-lg text-[10px] font-bold">
                                        <Layers class="h-3 w-3" />
                                        {{ mod.ingredient.name }} ({{ Number(mod.usage_qty) }} {{ mod.ingredient.unit }})
                                    </span>
                                    <span v-else class="text-slate-400 text-[10px] font-bold">
                                        -
                                    </span>
                                </td>
                                <td class="p-4 max-w-xs">
                                    <div class="flex flex-wrap gap-1">
                                        <span 
                                            v-for="p in mod.products" 
                                            :key="p.id" 
                                            class="inline-block px-1.5 py-0.5 bg-slate-100 dark:bg-slate-800 text-slate-650 dark:text-slate-350 rounded text-[9px] font-bold"
                                        >
                                            {{ p.name }}
                                        </span>
                                        <span v-if="!mod.products || mod.products.length === 0" class="text-rose-500 text-[10px] font-extrabold">
                                            Belum dikaitkan produk
                                        </span>
                                    </div>
                                </td>
                                <td class="p-4">
                                    <span 
                                        :class="[
                                            'px-2 py-0.5 rounded-full text-[9px] font-extrabold uppercase',
                                            mod.is_active ? 'bg-emerald-50 dark:bg-emerald-950/20 border border-emerald-200/30 text-emerald-700 dark:text-emerald-450' : 'bg-slate-100 dark:bg-slate-800 text-slate-400 dark:text-slate-500'
                                        ]"
                                    >
                                        {{ mod.is_active ? 'Aktif' : 'Nonaktif' }}
                                    </span>
                                </td>
                                <td class="p-4">
                                    <div class="flex items-center justify-center gap-2">
                                        <button
                                            @click="openEditModal(mod)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-[#8c5a3c] rounded-lg transition-colors cursor-pointer"
                                            title="Ubah"
                                        >
                                            <Pencil class="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            @click="deleteModifier(mod)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-400 hover:text-rose-600 rounded-lg transition-colors cursor-pointer"
                                            title="Hapus"
                                        >
                                            <Trash2 class="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination Footer -->
                <div v-if="modifiers.last_page > 1" class="p-4 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <span class="text-xs text-slate-500">
                        Menampilkan Halaman {{ modifiers.current_page }} dari {{ modifiers.last_page }} (Total {{ modifiers.total }} data)
                    </span>
                    <div class="flex items-center gap-1">
                        <Link
                            v-for="link in modifiers.links"
                            :key="link.label"
                            :href="link.url || '#'"
                            :class="[
                                'px-3 py-1 text-xs border rounded-lg transition-colors font-bold',
                                link.active ? 'bg-[#8c5a3c] border-[#8c5a3c] text-white' : 'border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 text-slate-600 dark:text-slate-400',
                                !link.url ? 'opacity-50 pointer-events-none' : 'cursor-pointer'
                            ]"
                            v-html="link.label"
                        />
                    </div>
                </div>
            </div>
        </div>

        <!-- Add/Edit Modal -->
        <div v-if="isModalOpen" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/65 backdrop-blur-sm animate-in fade-in duration-150">
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col transform transition-all font-sans">
                <!-- 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 flex items-center gap-2">
                        <PlusCircle class="h-4 w-4 text-[#8c5a3c]" />
                        <span>{{ modalTitle }}</span>
                    </h3>
                    <button @click="isModalOpen = 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 form body -->
                <form @submit.prevent="handleSubmit" class="flex-1 overflow-y-auto max-h-[70vh] p-6 space-y-5">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <!-- Left column: Details -->
                        <div class="space-y-4">
                            <!-- Name -->
                            <div class="space-y-1.5">
                                <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Nama Add-on</label>
                                <input
                                    v-model="form.name"
                                    type="text"
                                    required
                                    placeholder="Contoh: Extra Cheese, Oat Milk"
                                    class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                                />
                                <span v-if="form.errors.name" class="text-[10px] text-rose-500 font-bold block">{{ form.errors.name }}</span>
                            </div>

                            <!-- Price -->
                            <div class="space-y-1.5">
                                <label class="block text-xs font-bold text-slate-650 dark:text-slate-350">Harga Tambahan (Rp)</label>
                                <input
                                    v-model.number="form.price"
                                    type="number"
                                    required
                                    min="0"
                                    placeholder="0"
                                    class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150 font-bold"
                                />
                                <span v-if="form.errors.price" class="text-[10px] text-rose-500 font-bold block">{{ form.errors.price }}</span>
                            </div>

                            <!-- Link to Inventory Ingredient (Optional) -->
                            <div class="p-4 bg-slate-50 dark:bg-slate-900/30 border border-slate-200 dark:border-slate-800 rounded-xl space-y-3">
                                <h4 class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                                    <Layers class="h-3.5 w-3.5 text-amber-500" />
                                    <span>Hubungkan ke Bahan Baku (Opsional)</span>
                                </h4>
                                <p class="text-[10px] text-slate-500 dark:text-slate-400">
                                    Jika dihubungkan, stok bahan baku ini akan berkurang otomatis setiap kali add-on ini terjual.
                                </p>

                                <div class="space-y-1.5">
                                    <label class="block text-[10px] font-bold text-slate-500">Pilih Bahan Baku</label>
                                    <select
                                        v-model="form.ingredient_id"
                                        class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-800 dark:text-slate-200"
                                    >
                                        <option :value="null">-- Tidak Ada Pengurangan Stok --</option>
                                        <option v-for="ing in ingredients" :key="ing.id" :value="ing.id">{{ ing.name }} ({{ ing.unit }})</option>
                                    </select>
                                </div>

                                <div class="space-y-1.5" v-if="form.ingredient_id">
                                    <label class="block text-[10px] font-bold text-slate-500">Jumlah Pemakaian per Porsi</label>
                                    <div class="flex items-center gap-2">
                                        <input
                                            v-model.number="form.usage_qty"
                                            type="number"
                                            step="0.0001"
                                            required
                                            min="0.0001"
                                            placeholder="Jumlah"
                                            class="w-full px-3 py-2 text-xs border border-slate-200 dark:border-slate-800 rounded-lg bg-transparent focus:outline-none focus:ring-1 focus:ring-[#8c5a3c] text-slate-850 dark:text-slate-150"
                                        />
                                        <span class="text-xs text-slate-400 font-bold">
                                            {{ ingredients.find(i => i.id === form.ingredient_id)?.unit }}
                                        </span>
                                    </div>
                                    <span v-if="form.errors.usage_qty" class="text-[10px] text-rose-500 font-bold block">{{ form.errors.usage_qty }}</span>
                                </div>
                            </div>

                            <!-- Status Toggle -->
                            <div class="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-900/30 border border-slate-200 dark:border-slate-800 rounded-xl">
                                <div class="space-y-0.5">
                                    <label class="block text-xs font-bold text-slate-850 dark:text-slate-150">Status Add-on</label>
                                    <span class="text-[10px] text-slate-400">Aktifkan agar dapat dipilih saat transaksi.</span>
                                </div>
                                <label class="relative inline-flex items-center cursor-pointer select-none">
                                    <input 
                                        type="checkbox" 
                                        v-model="form.is_active" 
                                        class="sr-only peer"
                                    />
                                    <div class="w-10 h-5 bg-slate-200 dark:bg-slate-800 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-slate-600 peer-checked:bg-[#8c5a3c]"></div>
                                </label>
                            </div>
                        </div>

                        <!-- Right column: Product Association List -->
                        <div class="flex flex-col border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden bg-slate-50/50 dark:bg-slate-900/10">
                            <div class="p-3.5 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/20 flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <Coffee class="h-4 w-4 text-[#8c5a3c]" />
                                    <span class="text-xs font-extrabold text-slate-900 dark:text-slate-100">Kaitkan ke Produk</span>
                                </div>
                                <span class="text-[10px] font-bold text-slate-450">
                                    {{ form.product_ids.length }} produk dipilih
                                </span>
                            </div>

                            <div class="p-4 space-y-4 flex-1 overflow-y-auto max-h-[360px]">
                                <div v-if="products.length === 0" class="text-center py-8 text-slate-400 text-xs font-medium">
                                    Belum ada data produk tersedia.
                                </div>
                                
                                <div 
                                    v-for="(prods, cat) in groupedProducts" 
                                    :key="cat"
                                    class="space-y-2 border-b border-slate-200/50 dark:border-slate-800/40 pb-3 last:border-0 last:pb-0"
                                >
                                    <!-- Category Checkbox / Header -->
                                    <div class="flex items-center justify-between">
                                        <span class="text-[10px] font-black uppercase tracking-wider text-slate-400 flex items-center gap-1">
                                            <Tag class="h-3 w-3" />
                                            {{ cat }}
                                        </span>
                                        <button
                                            type="button"
                                            @click="toggleCategoryProducts(cat, !isCategoryFullySelected(cat))"
                                            class="text-[9px] font-bold text-[#8c5a3c] hover:underline cursor-pointer"
                                        >
                                            {{ isCategoryFullySelected(cat) ? 'Pilih Semua' : 'Batal Semua' }}
                                        </button>
                                    </div>

                                    <!-- Products Grid -->
                                    <div class="grid grid-cols-1 gap-2 pt-1">
                                        <label 
                                            v-for="prod in prods" 
                                            :key="prod.id"
                                            class="flex items-center gap-2.5 p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 border border-slate-200/40 dark:border-slate-800/30 text-xs font-bold text-slate-700 dark:text-slate-300 cursor-pointer select-none transition-colors"
                                        >
                                            <input
                                                type="checkbox"
                                                v-model="form.product_ids"
                                                :value="prod.id"
                                                class="h-3.5 w-3.5 rounded border-slate-300 text-[#8c5a3c] focus:ring-[#8c5a3c]"
                                            />
                                            <div class="flex-1 flex items-center justify-between">
                                                <span>{{ prod.name }}</span>
                                                <span class="text-[10px] text-slate-400">Rp{{ Number(prod.price).toLocaleString('id-ID') }}</span>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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