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

interface Item {
    id: number;
    name: string;
    unit?: string;
}

interface WasteData {
    id: number;
    outlet_id: number;
    outlet_name: string;
    user_name: string;
    item_type: 'Ingredient' | 'Product';
    item_id: number;
    name: string;
    qty: number;
    notes: string | null;
    created_at: string;
}

interface PaginatedWastes {
    data: WasteData[];
    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 Outlet {
    id: number;
    name: string;
}

const props = defineProps<{
    wastes: PaginatedWastes;
    outlets: Outlet[];
    ingredients: Item[];
    products: Item[];
    filters: {
        outlet_id?: string;
    };
}>();

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

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

// Modal state
const isFormModalOpen = ref(false);

// Form config
const form = useForm({
    outlet_id: selectedOutletId.value ? Number(selectedOutletId.value) : 0,
    item_type: 'Ingredient',
    item_id: '',
    qty: 0,
    notes: '',
});

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

const submitForm = () => {
    form.post(route('wastes.store'), {
        onSuccess: () => {
            isFormModalOpen.value = false;
            form.reset();
        },
    });
};

const deleteWaste = (waste: WasteData) => {
    if (confirm('Apakah Anda yakin ingin menghapus catatan waste ini? Tindakan ini akan mengembalikan jumlah stok.')) {
        router.delete(route('wastes.destroy', waste.id));
    }
};

const activeItemsList = computed(() => {
    if (form.item_type === 'Ingredient') return props.ingredients;
    return props.products;
});

const getItemUnit = (itemType: string, itemId: string) => {
    if (!itemId) return '';
    if (itemType === 'Ingredient') {
        const ing = props.ingredients.find(i => String(i.id) === itemId);
        return ing?.unit || '';
    }
    return 'pcs';
};
</script>

<template>
    <Head title="Waste Management (Stok Terbuang)" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl font-extrabold text-slate-900 dark:text-slate-50 tracking-tight">
                        Waste Management
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Pencatatan barang yang kedaluwarsa, tumpah, atau rusak untuk pemantauan akurasi stok dan biaya terbuang.
                    </p>
                </div>
                <button
                    @click="openCreateModal"
                    class="flex items-center justify-center gap-2 px-4 py-2 bg-[#8c5a3c] hover:bg-[#734a31] text-white text-sm font-bold rounded-xl transition-all cursor-pointer shadow-lg shadow-[#8c5a3c]/10"
                >
                    <Plus class="h-4 w-4" />
                    Catat Waste Baru
                </button>
            </div>

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

            <!-- Wastes List -->
            <div v-if="wastes.data.length > 0" class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse">
                        <thead>
                            <tr class="border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Item Wasted</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Tipe</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Jumlah (Qty)</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Keterangan / Alasan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Petugas</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Tanggal</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <tr v-for="w in wastes.data" :key="w.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4">
                                    <span class="font-extrabold text-xs text-slate-800 dark:text-slate-100">{{ w.name }}</span>
                                </td>
                                <td class="px-6 py-4">
                                    <span v-if="w.item_type === 'Ingredient'" class="px-2 py-0.5 border border-[#8c5a3c]/20 bg-[#8c5a3c]/10 text-[#8c5a3c] rounded text-[9px] font-extrabold uppercase">
                                        Bahan Baku
                                    </span>
                                    <span v-else class="px-2 py-0.5 border border-indigo-500/20 bg-indigo-500/10 text-indigo-500 rounded text-[9px] font-extrabold uppercase">
                                        Retail
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-xs font-bold text-slate-700 dark:text-slate-300 text-right">
                                    {{ w.qty }} {{ w.item_type === 'Ingredient' ? 'g/ml/pcs' : 'pcs' }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-500">
                                    {{ w.notes || '-' }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-655 dark:text-slate-350">
                                    <div class="flex items-center gap-1.5">
                                        <User class="h-3.5 w-3.5 text-slate-400" />
                                        <span>{{ w.user_name }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-[11px] text-slate-400">
                                    <div class="flex items-center gap-1.5">
                                        <Calendar class="h-3.5 w-3.5 text-slate-450" />
                                        <span>{{ new Date(w.created_at).toLocaleString('id-ID', { dateStyle: 'medium', timeStyle: 'short' }) }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <button
                                        @click="deleteWaste(w)"
                                        class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-rose-600 rounded-lg cursor-pointer"
                                    >
                                        <Trash2 class="h-3.5 w-3.5" />
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

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

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

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

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Tipe Item</label>
                                <select
                                    v-model="form.item_type"
                                    required
                                    class="w-full h-10 px-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c] cursor-pointer"
                                >
                                    <option value="Ingredient">Bahan Baku</option>
                                    <option value="Product">Produk Retail</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Jumlah Terbuang (Qty)</label>
                                <div class="relative flex items-center">
                                    <input
                                        type="number"
                                        step="0.0001"
                                        v-model="form.qty"
                                        required
                                        min="0.0001"
                                        class="w-full h-10 pl-3 pr-10 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                                    />
                                    <span class="absolute right-3 text-[10px] font-bold text-slate-400 uppercase">
                                        {{ getItemUnit(form.item_type, form.item_id) }}
                                    </span>
                                </div>
                            </div>
                        </div>

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

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Alasan / Catatan</label>
                            <textarea
                                v-model="form.notes"
                                placeholder="Contoh: Expired 28 Juni, Tumpah di bar, Rusak saji..."
                                rows="3"
                                class="w-full p-3 border border-slate-200 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800 text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#8c5a3c]/20 focus:border-[#8c5a3c]"
                            ></textarea>
                        </div>

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