<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, Package, Scale, Edit2, Trash2, Plus, AlertCircle, PlusCircle, CheckCircle2, X, History } from 'lucide-vue-next';

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

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

interface IngredientData {
    id: number;
    name: string;
    unit: string;
    outlet_ingredients: OutletIngredientStock[];
    created_at: string;
}

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

interface StockTransaction {
    id: number;
    outlet_id: number;
    user_id: number;
    supplier_id: number | null;
    item_type: string;
    item_id: number;
    qty: string | number;
    type: string; // 'add' or 'set'
    notes: string | null;
    created_at: string;
    outlet: { name: string };
    user: { name: string };
    supplier: { name: string } | null;
    ingredient: { name: string; unit: string } | null;
}

interface PaginatedHistory {
    data: StockTransaction[];
    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<{
    ingredients: PaginatedIngredients;
    outlets: Outlet[];
    suppliers: Supplier[];
    history: PaginatedHistory;
    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('ingredients.index'),
            { search: search.value },
            { preserveState: true, replace: true }
        );
    }, 400);
});

// Tab Navigation state
const activeTab = ref<'ingredients' | 'history'>(
    typeof window !== 'undefined' && new URLSearchParams(window.location.search).has('history_page') ? 'history' : 'ingredients'
);

// Modal states
const isFormModalOpen = ref(false);
const isDeleteModalOpen = ref(false);
const isAdjustModalOpen = ref(false);
const isDeleteTransactionModalOpen = ref(false);

const editingIngredient = ref<IngredientData | null>(null);
const ingredientToDelete = ref<IngredientData | null>(null);
const transactionToDelete = ref<StockTransaction | null>(null);

// Forms
const form = useForm({
    name: '',
    unit: '',
});

const adjustForm = useForm({
    outlet_id: '',
    ingredient_id: '',
    stock_qty: 0,
    threshold_qty: 0,
    action_type: 'add', // add or set
    supplier_id: '',
    notes: '',
});

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

const openEditModal = (ing: IngredientData) => {
    editingIngredient.value = ing;
    form.clearErrors();
    form.name = ing.name;
    form.unit = ing.unit;
    isFormModalOpen.value = true;
};

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

const openDeleteModal = (ing: IngredientData) => {
    ingredientToDelete.value = ing;
    isDeleteModalOpen.value = true;
};

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

const openDeleteTransactionModal = (item: StockTransaction) => {
    transactionToDelete.value = item;
    isDeleteTransactionModalOpen.value = true;
};

const deleteTransaction = () => {
    if (!transactionToDelete.value) return;
    router.delete(route('ingredients.transactions.destroy', transactionToDelete.value.id), {
        onSuccess: () => {
            isDeleteTransactionModalOpen.value = false;
            transactionToDelete.value = null;
        },
    });
};

const openAdjustModal = (ing: IngredientData, outletStock?: OutletIngredientStock) => {
    adjustForm.clearErrors();
    adjustForm.ingredient_id = String(ing.id);
    adjustForm.supplier_id = outletStock && outletStock.last_supplier_id ? String(outletStock.last_supplier_id) : '';
    adjustForm.notes = '';
    
    if (outletStock) {
        adjustForm.outlet_id = String(outletStock.outlet_id);
        adjustForm.stock_qty = 0;
        adjustForm.threshold_qty = Number(outletStock.threshold_qty);
        adjustForm.action_type = 'add';
    } else {
        adjustForm.outlet_id = props.outlets[0] ? String(props.outlets[0].id) : '';
        adjustForm.stock_qty = 0;
        adjustForm.threshold_qty = 0;
        adjustForm.action_type = 'add';
    }
    
    isAdjustModalOpen.value = true;
};

const submitAdjustForm = () => {
    adjustForm.post(route('ingredients.adjust'), {
        onSuccess: () => {
            isAdjustModalOpen.value = false;
            adjustForm.reset();
        },
    });
};

const getIngredientName = (id: string | number) => {
    const ing = props.ingredients.data.find(i => i.id === Number(id));
    return ing ? ing.name : 'Ingredient';
};

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

const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('id-ID', {
        dateStyle: 'medium',
        timeStyle: 'short',
    });
};
</script>

<template>
    <Head title="Stock Inventory" />

    <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">Stock Inventory</h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Manage raw coffee beans, milk, syrups, cups, and track their stock levels across all outlets.
                    </p>
                </div>
                <div class="flex items-center gap-3">
                    <button
                        @click="isAdjustModalOpen = true; adjustForm.reset();"
                        class="inline-flex items-center justify-center gap-2 px-4 py-2.5 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-white dark:bg-slate-950"
                    >
                        <PlusCircle class="h-4 w-4 text-red-500" />
                        <span>Restock Stock</span>
                    </button>
                    <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>Add Ingredient</span>
                    </button>
                </div>
            </div>

            <!-- Tab Switcher Navigation -->
            <div class="border-b border-slate-200 dark:border-slate-800">
                <nav class="flex gap-6 -mb-px" aria-label="Tabs">
                    <button
                        @click="activeTab = 'ingredients'"
                        :class="[
                            'pb-4 text-sm font-bold border-b-2 transition-all cursor-pointer bg-transparent border-0 flex items-center gap-2 px-1',
                            activeTab === 'ingredients'
                                ? 'border-red-600 text-red-600 dark:text-red-500'
                                : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-250 hover:border-slate-300 dark:hover:border-slate-700'
                        ]"
                    >
                        <Package class="h-4 w-4" />
                        <span>Bahan Baku (Ingredients)</span>
                    </button>
                    <button
                        @click="activeTab = 'history'"
                        :class="[
                            'pb-4 text-sm font-bold border-b-2 transition-all cursor-pointer bg-transparent border-0 flex items-center gap-2 px-1',
                            activeTab === 'history'
                                ? 'border-red-600 text-red-600 dark:text-red-500'
                                : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-250 hover:border-slate-300 dark:hover:border-slate-700'
                        ]"
                    >
                        <History class="h-4 w-4" />
                        <span>Riwayat Restock & Penyesuaian</span>
                    </button>
                </nav>
            </div>

            <!-- Table Card -->
            <div v-if="activeTab === 'ingredients'" class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <!-- Search -->
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <div class="relative max-w-md 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 ingredients..."
                            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>
                </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">Ingredient Name</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Measure Unit</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Outlet Stock Levels</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="ingredients.data.length === 0">
                                <td colspan="4" class="p-8 text-center text-sm text-slate-500 dark:text-slate-400">
                                    No ingredients registered. Create one to begin.
                                </td>
                            </tr>
                            <tr 
                                v-for="ing in ingredients.data" 
                                :key="ing.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors align-top"
                            >
                                <td class="p-4 font-semibold text-sm text-slate-900 dark:text-slate-100">
                                    <div class="flex items-center gap-2.5">
                                        <div class="h-8 w-8 rounded-lg bg-red-50 dark:bg-red-950/20 flex items-center justify-center text-red-600 dark:text-red-400">
                                            <Package class="h-4.5 w-4.5" />
                                        </div>
                                        <span>{{ ing.name }}</span>
                                    </div>
                                </td>
                                <td class="p-4 text-sm text-slate-600 dark:text-slate-400 font-medium">
                                    <div class="flex items-center gap-1">
                                        <Scale class="h-4 w-4 text-slate-400" />
                                        <span>{{ ing.unit }}</span>
                                    </div>
                                </td>
                                <td class="p-4 text-sm">
                                    <div v-if="ing.outlet_ingredients.length === 0" class="text-xs text-slate-400 italic">
                                        No stock levels configured. Restock this ingredient.
                                    </div>
                                    <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-lg">
                                        <div 
                                            v-for="stock in ing.outlet_ingredients" 
                                            :key="stock.id"
                                            @click="openAdjustModal(ing, stock)"
                                            class="p-2.5 rounded-lg border border-slate-100 dark:border-slate-900 bg-slate-50/30 dark:bg-slate-900/10 hover:border-red-500/40 hover:bg-slate-100/50 dark:hover:bg-slate-900/40 transition-all cursor-pointer flex flex-col"
                                        >
                                            <div class="flex items-center justify-between gap-2">
                                                <span class="font-medium text-xs text-slate-800 dark:text-slate-200 truncate">{{ stock.outlet.name }}</span>
                                                <span 
                                                    v-if="isLowStock(Number(stock.stock_qty), Number(stock.threshold_qty))"
                                                    class="inline-flex px-1.5 py-0.5 rounded text-[9px] font-bold uppercase bg-amber-50 dark:bg-amber-950/30 text-amber-700 dark:text-amber-400 flex-shrink-0"
                                                >
                                                    Low
                                                </span>
                                            </div>
                                            <div class="flex items-baseline gap-1 mt-1.5">
                                                <span class="text-sm font-bold" :class="isLowStock(Number(stock.stock_qty), Number(stock.threshold_qty)) ? 'text-amber-600 dark:text-amber-400' : 'text-slate-900 dark:text-slate-100'">
                                                    {{ Number(stock.stock_qty).toLocaleString('id-ID') }}
                                                </span>
                                                <span class="text-[10px] text-slate-400">{{ ing.unit }}</span>
                                                <span class="text-[10px] text-slate-400 dark:text-slate-500 ml-auto">(min: {{ Number(stock.threshold_qty).toLocaleString('id-ID') }})</span>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="p-4 text-right">
                                    <div class="flex items-center justify-end gap-1">
                                        <button
                                            @click="openEditModal(ing)"
                                            class="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-950 text-slate-500 dark:text-slate-400 hover:text-slate-800 dark:hover:text-slate-100 cursor-pointer"
                                            title="Edit Item"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </button>
                                        <button
                                            @click="openDeleteModal(ing)"
                                            class="p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-955/20 text-rose-500 hover:text-rose-600 cursor-pointer"
                                            title="Delete Item"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div v-if="ingredients.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 {{ ingredients.data.length }} of {{ ingredients.total }} ingredients</p>
                    <div class="flex gap-2">
                        <Link
                            v-if="ingredients.prev_page_url"
                            :href="ingredients.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="ingredients.next_page_url"
                            :href="ingredients.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>

            <!-- Restock & Adjustment History Card -->
            <div v-if="activeTab === 'history'" class="bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm overflow-hidden">
                <!-- Header -->
                <div class="p-5 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between">
                    <div>
                        <h2 class="text-base font-bold text-slate-900 dark:text-slate-50 flex items-center gap-2">
                            <History class="h-4.5 w-4.5 text-red-500" />
                            <span>Restock & Adjustment History</span>
                        </h2>
                        <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">
                            A list of raw material restocking and inventory adjustment activities across all outlets.
                        </p>
                    </div>
                </div>

                <!-- Table -->
                <div class="overflow-x-auto">
                    <table class="w-full border-collapse text-left text-sm">
                        <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 whitespace-nowrap">Date & Time</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Ingredient</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Outlet</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Type</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Quantity</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Supplier</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Operator</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap">Notes</th>
                                <th class="p-4 text-xs font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400 text-right whitespace-nowrap">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-200 dark:divide-slate-800">
                            <tr v-if="history.data.length === 0">
                                <td colspan="9" class="p-8 text-center text-sm text-slate-500 dark:text-slate-400">
                                    No restock history recorded yet.
                                </td>
                            </tr>
                            <tr 
                                v-for="item in history.data" 
                                :key="item.id"
                                class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-colors"
                            >
                                <td class="p-4 text-slate-500 dark:text-slate-400 whitespace-nowrap text-xs">
                                    {{ formatDateTime(item.created_at) }}
                                </td>
                                <td class="p-4 font-semibold text-slate-900 dark:text-slate-100 text-sm whitespace-nowrap">
                                    {{ item.ingredient?.name || 'Deleted Ingredient' }}
                                </td>
                                <td class="p-4 text-slate-700 dark:text-slate-300 text-sm whitespace-nowrap">
                                    {{ item.outlet?.name }}
                                </td>
                                <td class="p-4 whitespace-nowrap">
                                    <span 
                                        v-if="item.type === 'add'"
                                        class="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-400 border border-emerald-500/20 whitespace-nowrap"
                                    >
                                        Restock (+Qty)
                                    </span>
                                    <span 
                                        v-else
                                        class="inline-flex px-2 py-0.5 rounded text-[10px] font-semibold bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400 border border-blue-500/20 whitespace-nowrap"
                                    >
                                        Override (=Qty)
                                    </span>
                                </td>
                                <td class="p-4 font-bold text-slate-900 dark:text-slate-100 text-sm whitespace-nowrap">
                                    {{ Number(item.qty).toLocaleString('id-ID') }}
                                    <span class="text-xs font-normal text-slate-400 ml-1">{{ item.ingredient?.unit }}</span>
                                </td>
                                <td class="p-4 text-slate-600 dark:text-slate-400 text-xs whitespace-nowrap">
                                    {{ item.supplier?.name || '-' }}
                                </td>
                                <td class="p-4 text-slate-600 dark:text-slate-400 text-xs whitespace-nowrap">
                                    {{ item.user?.name }}
                                </td>
                                <td class="p-4 text-xs text-slate-500 dark:text-slate-400 max-w-[200px] truncate whitespace-nowrap" :title="item.notes || undefined">
                                    {{ item.notes || '-' }}
                                </td>
                                <td class="p-4 text-right">
                                    <button
                                        @click="openDeleteTransactionModal(item)"
                                        class="p-1.5 rounded-lg hover:bg-rose-50 dark:hover:bg-rose-955/20 text-rose-500 hover:text-rose-600 cursor-pointer animate-all"
                                        title="Delete Log & Revert Stock"
                                    >
                                        <Trash2 class="h-4 w-4" />
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div v-if="history.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 {{ history.data.length }} of {{ history.total }} items</p>
                    <div class="flex gap-2">
                        <Link
                            v-if="history.prev_page_url"
                            :href="history.prev_page_url"
                            :preserve-scroll="true"
                            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="history.next_page_url"
                            :href="history.next_page_url"
                            :preserve-scroll="true"
                            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>

        <!-- 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-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">
                    <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">
                        {{ editingIngredient ? 'Edit Ingredient' : 'Add New Ingredient' }}
                    </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="space-y-1">
                        <label for="name" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Ingredient Name</label>
                        <input
                            id="name"
                            v-model="form.name"
                            type="text"
                            required
                            placeholder="e.g. Biji Kopi Arabika"
                            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="form.errors.name" class="text-xs text-rose-600 mt-1">{{ form.errors.name }}</p>
                    </div>

                    <div class="space-y-1">
                        <label for="unit" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Measurement Unit</label>
                        <input
                            id="unit"
                            v-model="form.unit"
                            type="text"
                            required
                            placeholder="e.g. g, ml, pcs, kg"
                            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="form.errors.unit" class="text-xs text-rose-600 mt-1">{{ form.errors.unit }}</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="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 Ingredient' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Adjust / Restock Modal -->
        <div v-if="isAdjustModalOpen" 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 flex flex-col max-h-[90vh] 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 flex-shrink-0">
                    <div>
                        <h3 class="text-lg font-bold text-slate-900 dark:text-slate-50">Restock Stock Level</h3>
                        <p class="text-xs text-slate-400 mt-0.5" v-if="adjustForm.ingredient_id">
                            Setting inventory for: <span class="font-bold text-slate-700 dark:text-slate-200">{{ getIngredientName(adjustForm.ingredient_id) }}</span>
                        </p>
                    </div>
                    <button @click="isAdjustModalOpen = 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="submitAdjustForm" class="flex flex-col flex-1 min-h-0">
                <div class="p-6 space-y-4 overflow-y-auto flex-1">
                    <!-- Ingredient selector if not pre-set -->
                    <div class="space-y-1" v-if="!adjustForm.ingredient_id">
                        <label for="adjust_ing" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Ingredient</label>
                        <select
                            id="adjust_ing"
                            v-model="adjustForm.ingredient_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 Ingredient</option>
                            <option v-for="ing in ingredients.data" :key="ing.id" :value="String(ing.id)">{{ ing.name }} ({{ ing.unit }})</option>
                        </select>
                        <p v-if="adjustForm.errors.ingredient_id" class="text-xs text-rose-600 mt-1">{{ adjustForm.errors.ingredient_id }}</p>
                    </div>

                    <!-- Outlet Selector -->
                    <div class="space-y-1">
                        <label for="adjust_outlet" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Target Outlet</label>
                        <select
                            id="adjust_outlet"
                            v-model="adjustForm.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="adjustForm.errors.outlet_id" class="text-xs text-rose-600 mt-1">{{ adjustForm.errors.outlet_id }}</p>
                    </div>

                    <!-- Adjust 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="adjustForm.action_type = 'add'"
                                :class="[
                                    'py-2 text-xs font-semibold rounded-lg border transition-all cursor-pointer',
                                    adjustForm.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="adjustForm.action_type = 'set'"
                                :class="[
                                    'py-2 text-xs font-semibold rounded-lg border transition-all cursor-pointer',
                                    adjustForm.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="adjust_qty" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Quantity</label>
                        <input
                            id="adjust_qty"
                            v-model.number="adjustForm.stock_qty"
                            type="number"
                            step="0.0001"
                            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="adjustForm.errors.stock_qty" class="text-xs text-rose-600 mt-1">{{ adjustForm.errors.stock_qty }}</p>
                    </div>

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

                    <!-- Supplier -->
                    <div class="space-y-1">
                        <label for="adjust_supplier" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Supplier</label>
                        <select
                            id="adjust_supplier"
                            v-model="adjustForm.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="adjustForm.errors.supplier_id" class="text-xs text-rose-600 mt-1">{{ adjustForm.errors.supplier_id }}</p>
                    </div>

                    <!-- Adjustment Notes -->
                    <div class="space-y-1">
                        <label for="adjust_notes" class="text-xs font-semibold uppercase text-slate-500 dark:text-slate-400">Adjustment Notes</label>
                        <textarea
                            id="adjust_notes"
                            v-model="adjustForm.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="adjustForm.errors.notes" class="text-xs text-rose-600 mt-1">{{ adjustForm.errors.notes }}</p>
                    </div>

                </div>
                    <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="isAdjustModalOpen = 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="adjustForm.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"
                        >
                            {{ adjustForm.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 Ingredient?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400">
                    Are you sure you want to delete ingredient <span class="font-bold text-slate-900 dark:text-slate-100">"{{ ingredientToDelete?.name }}"</span>? This will remove all associated recipes and stock records globally. 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="deleteIngredient"
                        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>
        <!-- Delete Stock Transaction Confirmation Modal -->
        <div v-if="isDeleteTransactionModalOpen" 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 History Log?</h3>
                </div>

                <p class="text-sm text-slate-500 dark:text-slate-400 leading-relaxed">
                    Are you sure you want to delete this stock transaction entry?
                    <span v-if="transactionToDelete?.type === 'add'" class="block mt-2 font-bold text-amber-600 dark:text-amber-400">
                        ⚠️ WARNING: Since this was a Restock (+Qty) transaction, the added quantity of 
                        {{ Number(transactionToDelete?.qty).toLocaleString('id-ID') }} 
                        will be automatically subtracted/reverted from the outlet's current inventory balance.
                    </span>
                </p>

                <div class="flex items-center justify-end gap-3 pt-2">
                    <button
                        @click="isDeleteTransactionModalOpen = 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="deleteTransaction"
                        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>
