<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { Head, useForm, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Search, Coffee, Plus, Edit2, Trash2, Sliders, AlertCircle, FileText, CheckCircle2, X } from 'lucide-vue-next';

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

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

interface RecipeItem {
    id?: number;
    ingredient_id: number;
    usage_qty: string | number;
    variant: string | null;
    ingredient?: Ingredient;
}

interface OutletProductStock {
    id: number;
    outlet_id: number;
    product_id: number;
    stock_qty: string | number;
    threshold_qty: string | number;
    last_supplier_id: number | null;
    outlet: {
        id: number;
        name: string;
    };
}

interface ProductData {
    id: number;
    name: string;
    price: string | number;
    category: string;
    description: string | null;
    image_path: string | null;
    is_active: boolean;
    recipes: RecipeItem[];
    outlet_products: OutletProductStock[];
    created_at: string;
}

interface PaginatedProducts {
    data: ProductData[];
    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 }[];
}

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

const props = defineProps<{
    products: PaginatedProducts;
    ingredients: Ingredient[];
    outlets: Outlet[];
    suppliers: Supplier[];
    filters: {
        search?: string;
        category?: string;
    };
}>();

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

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

watch(search, applyFilters);
watch(categoryFilter, applyFilters);

// Categories list
const defaultCategories = ['Coffee', 'Non-Coffee', 'Food', 'Snacks', 'Dessert', 'Bakery', 'Retail', 'Other'];
const categories = computed(() => {
    const fromProducts = props.products?.data ? props.products.data.map(p => p.category) : [];
    const set = new Set([...defaultCategories, ...fromProducts]);
    return Array.from(set).filter(Boolean);
});

// Modals
const isFormModalOpen = ref(false);
const isDeleteModalOpen = ref(false);
const isRecipeModalOpen = ref(false);
const isStockModalOpen = ref(false);

const editingProduct = ref<ProductData | null>(null);
const productToDelete = ref<ProductData | null>(null);
const recipeProduct = ref<ProductData | null>(null);
const stockProduct = ref<ProductData | null>(null);

// Forms
const form = useForm({
    name: '',
    price: 0,
    category: 'Coffee',
    description: '',
    image: null as File | null,
    is_active: true,
});

const recipeForm = useForm({
    recipes: [] as { ingredient_id: number; usage_qty: number; variant: string | null }[],
});

const stockForm = useForm({
    outlet_id: '',
    product_id: '',
    stock_qty: 0,
    threshold_qty: 0,
    action_type: 'add',
    supplier_id: '',
    notes: '',
});

// Image preview
const imagePreview = ref<string | null>(null);
const handleImageChange = (e: Event) => {
    const target = e.target as HTMLInputElement;
    if (target.files && target.files[0]) {
        const file = target.files[0];
        form.image = file;
        imagePreview.value = URL.createObjectURL(file);
    }
};

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

const openEditModal = (product: ProductData) => {
    editingProduct.value = product;
    imagePreview.value = product.image_path;
    form.clearErrors();
    form.name = product.name;
    form.price = Number(product.price);
    form.category = product.category;
    form.description = product.description || '';
    form.image = null;
    form.is_active = product.is_active;
    isFormModalOpen.value = true;
};

const submitForm = () => {
    if (editingProduct.value) {
        // Since Laravel patch requests have issues with files in Inertia, we send post with _method spoofing
        router.post(route('products.update', editingProduct.value.id), {
            _method: 'PUT',
            name: form.name,
            price: form.price,
            category: form.category,
            description: form.description,
            image: form.image,
            is_active: form.is_active ? 1 : 0,
        } as any, {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        form.post(route('products.store'), {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const openDeleteModal = (product: ProductData) => {
    productToDelete.value = product;
    isDeleteModalOpen.value = true;
};

const deleteProduct = () => {
    if (!productToDelete.value) return;
    router.delete(route('products.destroy', productToDelete.value.id), {
        onSuccess: () => {
            isDeleteModalOpen.value = false;
            productToDelete.value = null;
        },
    });
};

const openRecipeModal = (product: ProductData) => {
    recipeProduct.value = product;
    recipeForm.clearErrors();
    
    // Copy existing recipes
    recipeForm.recipes = product.recipes.map(r => ({
        ingredient_id: r.ingredient_id,
        usage_qty: Number(r.usage_qty),
        variant: r.variant,
    }));
    
    isRecipeModalOpen.value = true;
};

const addRecipeRow = () => {
    recipeForm.recipes.push({
        ingredient_id: props.ingredients[0] ? props.ingredients[0].id : 0,
        usage_qty: 1,
        variant: null,
    });
};

const removeRecipeRow = (idx: number) => {
    recipeForm.recipes.splice(idx, 1);
};

const submitRecipeForm = () => {
    if (!recipeProduct.value) return;
    recipeForm.post(route('products.recipe.save', recipeProduct.value.id), {
        onSuccess: () => {
            isRecipeModalOpen.value = false;
            recipeForm.reset();
        },
    });
};

const openStockModal = (product: ProductData, stockRecord?: OutletProductStock) => {
    stockProduct.value = product;
    stockForm.clearErrors();
    stockForm.product_id = String(product.id);
    stockForm.supplier_id = stockRecord && stockRecord.last_supplier_id ? String(stockRecord.last_supplier_id) : '';
    stockForm.notes = '';
    
    if (stockRecord) {
        stockForm.outlet_id = String(stockRecord.outlet_id);
        stockForm.stock_qty = 0;
        stockForm.threshold_qty = Number(stockRecord.threshold_qty);
        stockForm.action_type = 'add';
    } else {
        stockForm.outlet_id = props.outlets[0] ? String(props.outlets[0].id) : '';
        stockForm.stock_qty = 0;
        stockForm.threshold_qty = 0;
        stockForm.action_type = 'add';
    }
    
    isStockModalOpen.value = true;
};

const submitStockForm = () => {
    stockForm.post(route('products.adjust'), {
        onSuccess: () => {
            isStockModalOpen.value = false;
            stockForm.reset();
        },
    });
};

const getIngredientUnit = (id: number) => {
    const ing = props.ingredients.find(i => i.id === id);
    return ing ? ing.unit : '';
};

const getProductInitials = (name: string) => {
    return name.slice(0, 2).toUpperCase();
};

const isLowStock = (stock: number, threshold: number) => {
    return Number(stock) <= Number(threshold);
};
</script>

<template>
    <Head title="Product Catalog" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header Section -->
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight text-slate-900 dark:text-slate-50">Product Catalog</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Manage beverage recipes (BOM), snacks retail inventory, pricing, and active menu items.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="inline-flex items-center justify-center gap-2 px-4 py-2.5 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 transition-all cursor-pointer"
                >
                    <Plus class="h-4 w-4" />
                    <span>Create Product</span>
                </button>
            </div>

            <!-- Table Card -->
            <div class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <!-- Filters -->
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex flex-col md:flex-row items-center gap-4">
                    <div class="relative flex-1 w-full">
                        <Search class="absolute left-3 top-2.5 h-4 w-4 text-slate-400" />
                        <input
                            v-model="search"
                            type="text"
                            placeholder="Search products name or description..."
                            class="w-full pl-9 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"
                        />
                    </div>
                    <select
                        v-model="categoryFilter"
                        class="w-full md:w-48 px-3 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"
                    >
                        <option value="">All Categories</option>
                        <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
                    </select>
                </div>

                <!-- Table Content -->
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left">
                        <thead>
                            <tr class="border-b border-slate-200 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/30">
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Product</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Price</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Stock Type</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Recipe / Stock Info</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Status</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
                            <tr v-if="products.data.length === 0">
                                <td colspan="6" class="p-8 text-center text-sm text-slate-500 dark:text-slate-400">
                                    No products found in the catalog.
                                </td>
                            </tr>
                            <tr 
                                v-for="product in products.data" 
                                :key="product.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors align-top"
                            >
                                <td class="p-4">
                                    <div class="flex items-center gap-3">
                                        <!-- Image Thumbnail -->
                                        <div v-if="product.image_path" class="h-12 w-12 rounded-lg overflow-hidden border border-slate-200 dark:border-slate-800 flex-shrink-0">
                                            <img :src="product.image_path" alt="Product Thumbnail" class="h-full w-full object-cover" />
                                        </div>
                                        <div v-else class="h-12 w-12 rounded-lg bg-gradient-to-br from-red-500/20 to-orange-500/20 text-red-600 dark:text-red-400 flex items-center justify-center font-bold text-sm flex-shrink-0">
                                            {{ getProductInitials(product.name) }}
                                        </div>
                                        <div>
                                            <p class="text-sm font-semibold text-slate-900 dark:text-slate-100">{{ product.name }}</p>
                                            <span class="inline-flex px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-100 dark:bg-slate-900 text-slate-600 dark:text-slate-400 mt-1">
                                                {{ product.category }}
                                            </span>
                                        </div>
                                    </div>
                                </td>
                                <td class="p-4 text-sm font-semibold text-slate-900 dark:text-slate-100">
                                    Rp {{ Number(product.price).toLocaleString('id-ID') }}
                                </td>
                                <td class="p-4 text-sm text-slate-600 dark:text-slate-400 font-medium">
                                    <span v-if="product.recipes.length > 0" class="inline-flex items-center gap-1.5 text-xs text-indigo-600 dark:text-indigo-400">
                                        <Sliders class="h-3.5 w-3.5" />
                                        Recipe (BOM)
                                    </span>
                                    <span v-else class="inline-flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400">
                                        <FileText class="h-3.5 w-3.5" />
                                        Retail Stock
                                    </span>
                                </td>
                                <td class="p-4 text-xs text-slate-600 dark:text-slate-400">
                                    <!-- Recipe ingredients -->
                                    <div v-if="product.recipes.length > 0" class="space-y-1">
                                        <div v-for="rec in product.recipes" :key="rec.id" class="flex items-center gap-1">
                                            <span class="font-medium text-slate-700 dark:text-slate-300">- {{ rec.ingredient?.name }}:</span>
                                            <span>{{ Number(rec.usage_qty) }}{{ rec.ingredient?.unit }}</span>
                                            <span v-if="rec.variant" class="px-1 bg-red-100 dark:bg-red-950/40 text-red-600 dark:text-red-400 text-[9px] rounded font-bold uppercase">{{ rec.variant }}</span>
                                        </div>
                                    </div>
                                    <!-- Manual product stock levels -->
                                    <div v-else class="space-y-1.5">
                                        <div v-if="product.outlet_products.length === 0" class="text-slate-400 italic">No outlet stock levels.</div>
                                        <div class="grid grid-cols-1 gap-1">
                                            <div 
                                                v-for="st in product.outlet_products" 
                                                :key="st.id" 
                                                @click="openStockModal(product, st)"
                                                class="flex items-center gap-2 px-2 py-1 rounded bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 hover:border-red-500/40 transition-colors cursor-pointer w-fit"
                                            >
                                                <span class="font-medium text-[10px]">{{ st.outlet.name }}:</span>
                                                <span class="font-bold" :class="isLowStock(Number(st.stock_qty), Number(st.threshold_qty)) ? 'text-amber-600 dark:text-amber-400' : 'text-slate-900 dark:text-slate-100'">
                                                    {{ Number(st.stock_qty) }}
                                                </span>
                                                <span v-if="isLowStock(Number(st.stock_qty), Number(st.threshold_qty))" class="text-[8px] font-bold text-amber-500 uppercase">Low</span>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="p-4 text-sm">
                                    <span 
                                        :class="[
                                            'inline-flex px-2 py-0.5 rounded-full text-xs font-semibold',
                                            product.is_active 
                                                ? 'bg-emerald-50 dark:bg-emerald-95/30 text-emerald-700 dark:text-emerald-400' 
                                                : 'bg-slate-100 dark:bg-slate-900 text-slate-500 dark:text-slate-400'
                                        ]"
                                    >
                                        {{ product.is_active ? 'Active' : 'Inactive' }}
                                    </span>
                                </td>
                                <td class="p-4 text-right">
                                    <div class="flex items-center justify-end gap-1">
                                        <button
                                            @click="openRecipeModal(product)"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-950 text-indigo-500 dark:text-indigo-400 hover:text-indigo-700 cursor-pointer"
                                            title="Configure BOM Recipe"
                                        >
                                            <Sliders class="h-4 w-4" />
                                        </button>
                                        <button
                                            @click="openEditModal(product)"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-900 text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-100 cursor-pointer"
                                            title="Edit Info"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </button>
                                        <button
                                            v-if="product.is_active"
                                            @click="openDeleteModal(product)"
                                            class="p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-950/20 text-rose-500 hover:text-rose-600 cursor-pointer"
                                            title="Delete Product"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div v-if="products.last_page > 1" class="p-4 border-t border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <p class="text-xs text-slate-500">Showing {{ products.data.length }} of {{ products.total }} products</p>
                    <div class="flex gap-2">
                        <Link
                            v-if="products.prev_page_url"
                            :href="products.prev_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Previous
                        </Link>
                        <Link
                            v-if="products.next_page_url"
                            :href="products.next_page_url"
                            class="px-3 py-1.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-lg text-xs font-semibold hover:bg-slate-50 dark:hover:bg-slate-800 transition-all text-slate-700 dark:text-slate-300 cursor-pointer"
                        >
                            Next
                        </Link>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product 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="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">
                <div class="p-6 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">
                        {{ editingProduct ? 'Edit Product Catalog' : 'Add Product to Catalog' }}
                    </h3>
                    <button @click="isFormModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-500 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submitForm" class="p-6 space-y-4">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div class="space-y-1">
                            <label for="name" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Product Name</label>
                            <input
                                id="name"
                                v-model="form.name"
                                type="text"
                                required
                                placeholder="e.g. Es Kopi Susu Aren"
                                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"
                            />
                        </div>

                        <div class="space-y-1">
                            <label for="price" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Price (IDR)</label>
                            <input
                                id="price"
                                v-model.number="form.price"
                                type="number"
                                required
                                min="0"
                                placeholder="e.g. 25000"
                                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"
                            />
                        </div>

                        <div class="space-y-1">
                            <label for="category" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Category</label>
                            <select
                                id="category"
                                v-model="form.category"
                                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"
                            >
                                <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
                            </select>
                        </div>

                        <div class="space-y-1 flex items-center pt-4 pl-1">
                            <input
                                id="is_active"
                                v-model="form.is_active"
                                type="checkbox"
                                class="rounded border-slate-350 dark:border-slate-800 text-red-600 focus:ring-red-500"
                            />
                            <label for="is_active" class="ml-2 text-sm font-semibold text-slate-700 dark:text-slate-300 cursor-pointer">
                                Active (Show in POS Catalog)
                            </label>
                        </div>
                    </div>

                    <div class="space-y-1">
                        <label for="description" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Product Description</label>
                        <textarea
                            id="description"
                            v-model="form.description"
                            rows="2"
                            placeholder="Optional product description..."
                            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 resize-none"
                        />
                    </div>

                    <!-- Image upload -->
                    <div class="space-y-2">
                        <label class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400 block">Product Image</label>
                        <div class="flex items-center gap-4">
                            <div class="h-20 w-20 rounded-lg border border-dashed border-slate-200 dark:border-slate-800 overflow-hidden flex items-center justify-center bg-slate-50/50 dark:bg-slate-900/30">
                                <img v-if="imagePreview" :src="imagePreview" alt="Preview" class="h-full w-full object-cover" />
                                <Coffee v-else class="h-8 w-8 text-slate-300" />
                            </div>
                            <div class="flex-1">
                                <input
                                    type="file"
                                    id="image"
                                    accept="image/*"
                                    class="hidden"
                                    @change="handleImageChange"
                                />
                                <label
                                    for="image"
                                    class="px-3.5 py-2 rounded-lg border border-slate-200 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-900 text-xs font-semibold text-slate-700 dark:text-slate-300 transition-colors cursor-pointer inline-block"
                                >
                                    Upload Photo
                                </label>
                                <p class="text-[10px] text-slate-400 mt-1">PNG, JPG, JPEG, or WEBP up to 2MB.</p>
                            </div>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-200 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-300 hover:bg-slate-50 dark:hover:bg-slate-900 rounded-lg text-sm font-semibold transition-all cursor-pointer"
                        >
                            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"
                        >
                            {{ form.processing ? 'Saving...' : 'Save Product' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Recipe Modal (BOM) -->
        <div v-if="isRecipeModalOpen" 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-2xl 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">
                <div class="p-6 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">Bill of Materials (BOM) Recipe</h3>
                        <p class="text-xs text-slate-400 mt-0.5">Configure ingredient requirements for: <span class="font-bold text-slate-700 dark:text-slate-200">{{ recipeProduct?.name }}</span></p>
                    </div>
                    <button @click="isRecipeModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-500 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submitRecipeForm" class="p-6 space-y-6">
                    <div class="space-y-4">
                        <div class="flex items-center justify-between">
                            <span class="text-xs font-bold uppercase text-slate-400">Recipe Composition</span>
                            <button
                                type="button"
                                @click="addRecipeRow"
                                class="inline-flex items-center gap-1 text-xs font-semibold text-red-600 dark:text-red-400 hover:text-red-500 cursor-pointer"
                            >
                                <Plus class="h-3.5 w-3.5" />
                                Add Ingredient Row
                            </button>
                        </div>

                        <div v-if="recipeForm.recipes.length === 0" class="p-8 text-center border border-dashed border-slate-200 dark:border-slate-800 rounded-xl text-slate-400 text-xs">
                            No recipe configured. This item will use manual retail stock mapping.
                        </div>

                        <div v-else class="max-h-60 overflow-y-auto space-y-3 pr-2">
                            <div 
                                v-for="(row, idx) in recipeForm.recipes" 
                                :key="idx" 
                                class="flex items-end gap-3 p-3 bg-slate-50 dark:bg-slate-900/30 rounded-xl border border-slate-100 dark:border-slate-800"
                            >
                                <!-- Ingredient Selector -->
                                <div class="flex-1 min-w-0">
                                    <label class="text-[10px] font-semibold text-slate-400 uppercase">Ingredient</label>
                                    <select
                                        v-model="row.ingredient_id"
                                        required
                                        class="w-full px-2 py-1.5 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 text-slate-900 dark:text-slate-100 mt-1"
                                    >
                                        <option v-for="ing in ingredients" :key="ing.id" :value="ing.id">{{ ing.name }} ({{ ing.unit }})</option>
                                    </select>
                                </div>

                                <!-- Usage Quantity -->
                                <div class="w-32">
                                    <label class="text-[10px] font-semibold text-slate-400 uppercase">Usage Qty ({{ getIngredientUnit(row.ingredient_id) }})</label>
                                    <input
                                        v-model.number="row.usage_qty"
                                        type="number"
                                        step="0.0001"
                                        required
                                        min="0.0001"
                                        class="w-full px-2 py-1.5 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 text-slate-900 dark:text-slate-100 mt-1"
                                    />
                                </div>

                                <!-- Variant (Optional) -->
                                <div class="w-32">
                                    <label class="text-[10px] font-semibold text-slate-400 uppercase">Variant Option</label>
                                    <select
                                        v-model="row.variant"
                                        class="w-full px-2 py-1.5 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 text-slate-900 dark:text-slate-100 mt-1"
                                    >
                                        <option :value="null">Base (All)</option>
                                        <option value="hot">Hot Only</option>
                                        <option value="ice">Ice Only</option>
                                    </select>
                                </div>

                                <!-- Remove -->
                                <button
                                    type="button"
                                    @click="removeRecipeRow(idx)"
                                    class="p-2 text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-905/20 rounded-lg flex-shrink-0 cursor-pointer"
                                >
                                    <Trash2 class="h-4 w-4" />
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
                        <button
                            type="button"
                            @click="isRecipeModalOpen = 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"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="recipeForm.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"
                        >
                            {{ recipeForm.processing ? 'Saving...' : 'Save Recipe BOM' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Product Stock Adjustment Modal -->
        <div v-if="isStockModalOpen" 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 overflow-hidden animate-in zoom-in-95 duration-200">
                <div class="p-6 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">Retail Stock Adjustment</h3>
                        <p class="text-xs text-slate-400 mt-0.5" v-if="stockProduct">
                            Setting manual inventory for: <span class="font-bold text-slate-700 dark:text-slate-200">{{ stockProduct.name }}</span>
                        </p>
                    </div>
                    <button @click="isStockModalOpen = false" class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-900 rounded-lg text-slate-500 cursor-pointer">
                        <X class="h-5 w-5" />
                    </button>
                </div>

                <form @submit.prevent="submitStockForm" class="p-6 space-y-4">
                    <!-- Outlet Selector -->
                    <div class="space-y-1">
                        <label for="stock_outlet" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Target Outlet</label>
                        <select
                            id="stock_outlet"
                            v-model="stockForm.outlet_id"
                            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"
                        >
                            <option value="">Select Outlet</option>
                            <option v-for="ot in outlets" :key="ot.id" :value="String(ot.id)">{{ ot.name }}</option>
                        </select>
                        <p v-if="stockForm.errors.outlet_id" class="text-xs text-rose-600 mt-1">{{ stockForm.errors.outlet_id }}</p>
                    </div>

                    <!-- Action Type -->
                    <div class="space-y-1">
                        <label class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400 block mb-1">Adjustment Action</label>
                        <div class="grid grid-cols-2 gap-2">
                            <button
                                type="button"
                                @click="stockForm.action_type = 'add'"
                                :class="[
                                    'py-2 text-xs font-semibold rounded-lg border transition-all cursor-pointer',
                                    stockForm.action_type === 'add'
                                        ? 'bg-red-50 dark:bg-red-95/10 border-red-500 text-red-600 dark:text-red-400'
                                        : 'border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400'
                                ]"
                            >
                                Add Stock (+Qty)
                            </button>
                            <button
                                type="button"
                                @click="stockForm.action_type = 'set'"
                                :class="[
                                    'py-2 text-xs font-semibold rounded-lg border transition-all cursor-pointer',
                                    stockForm.action_type === 'set'
                                        ? 'bg-red-50 dark:bg-red-95/10 border-red-500 text-red-600 dark:text-red-400'
                                        : 'border-slate-200 dark:border-slate-800 text-slate-600 dark:text-slate-400'
                                ]"
                            >
                                Set Absolute Stock (=Qty)
                            </button>
                        </div>
                    </div>

                    <!-- Stock Quantity -->
                    <div class="space-y-1">
                        <label for="stock_qty" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Quantity (pcs)</label>
                        <input
                            id="stock_qty"
                            v-model.number="stockForm.stock_qty"
                            type="number"
                            min="0"
                            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"
                        />
                        <p v-if="stockForm.errors.stock_qty" class="text-xs text-rose-600 mt-1">{{ stockForm.errors.stock_qty }}</p>
                    </div>

                    <!-- Safety Threshold Quantity -->
                    <div class="space-y-1">
                        <label for="stock_threshold" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Safety Threshold (Minimum Stock Alert)</label>
                        <input
                            id="stock_threshold"
                            v-model.number="stockForm.threshold_qty"
                            type="number"
                            min="0"
                            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"
                        />
                        <p v-if="stockForm.errors.threshold_qty" class="text-xs text-rose-600 mt-1">{{ stockForm.errors.threshold_qty }}</p>
                    </div>

                    <!-- Supplier -->
                    <div class="space-y-1">
                        <label for="stock_supplier" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Supplier</label>
                        <select
                            id="stock_supplier"
                            v-model="stockForm.supplier_id"
                            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"
                        >
                            <option value="">Select Supplier</option>
                            <option v-for="sp in suppliers" :key="sp.id" :value="String(sp.id)">{{ sp.name }}</option>
                        </select>
                        <p v-if="stockForm.errors.supplier_id" class="text-xs text-rose-600 mt-1">{{ stockForm.errors.supplier_id }}</p>
                    </div>

                    <!-- Adjustment Notes -->
                    <div class="space-y-1">
                        <label for="stock_notes" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Adjustment Notes</label>
                        <textarea
                            id="stock_notes"
                            v-model="stockForm.notes"
                            rows="2"
                            placeholder="e.g. Purchase order invoice number, batch code, expiry notes..."
                            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"
                        ></textarea>
                        <p v-if="stockForm.errors.notes" class="text-xs text-rose-600 mt-1">{{ stockForm.errors.notes }}</p>
                    </div>

                    <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
                        <button
                            type="button"
                            @click="isStockModalOpen = 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"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            :disabled="stockForm.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"
                        >
                            {{ stockForm.processing ? 'Saving...' : 'Save Stock' }}
                        </button>
                    </div>
                </form>
            </div>
        </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 Product?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400">
                    Are you sure you want to delete product <span class="font-bold text-slate-900 dark:text-slate-100">"{{ productToDelete?.name }}"</span>? This will permanently delete this product, its recipes, and stock records across all outlets. This action is irreversible.
                </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"
                    >
                        Cancel
                    </button>
                    <button
                        @click="deleteProduct"
                        class="px-4 py-2 bg-rose-600 hover:bg-rose-500 text-white rounded-lg text-sm font-semibold transition-all cursor-pointer"
                    >
                        Confirm Delete
                    </button>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
