<script setup lang="ts">
import { ref } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { ClipboardList, Plus, Store, Calendar, CheckCircle2, User, Eye, Trash2 } from 'lucide-vue-next';

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

interface OpnameData {
    id: number;
    outlet_id: number;
    user_id: number;
    status: 'draft' | 'completed';
    created_at: string;
    outlet?: Outlet;
    user?: { id: number; name: string };
}

interface PaginatedOpnames {
    data: OpnameData[];
    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<{
    opnames: PaginatedOpnames;
    outlets: Outlet[];
    filters: {
        outlet_id?: string;
    };
}>();

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

const handleFilter = () => {
    router.get(
        route('opnames.index'),
        { outlet_id: selectedOutletId.value },
        { preserveState: true, replace: true }
    );
};

const createOpname = () => {
    if (!selectedOutletId.value) return;
    router.post(route('opnames.store'), {
        outlet_id: Number(selectedOutletId.value)
    }, {
        onSuccess: () => {
            // Success response
        }
    });
};

const deleteOpname = (opname: OpnameData) => {
    if (confirm('Apakah Anda yakin ingin menghapus draf opname ini?')) {
        router.delete(route('opnames.destroy', opname.id));
    }
};

const getStatusBadge = (status: string) => {
    switch (status) {
        case 'draft': return 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20';
        case 'completed': return 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20';
        default: return 'bg-slate-500/10 text-slate-600 dark:text-slate-400 border-slate-500/20';
    }
};
</script>

<template>
    <Head title="Stock Opname (Audit Stok)" />

    <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-55 tracking-tight">
                        Stock Opname
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Audit stok bahan baku dan produk retail secara berkala untuk menyesuaikan stok sistem dengan fisik.
                    </p>
                </div>
                <button
                    @click="createOpname"
                    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" />
                    Mulai Audit Baru (Draf)
                </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 Filter -->
                <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"
                        @change="handleFilter"
                        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>

            <!-- Opnames List -->
            <div v-if="opnames.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">ID Audit</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Outlet</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Petugas Audit</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Tanggal Audit</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Status</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="op in opnames.data" :key="op.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4 text-xs font-bold text-[#8c5a3c]">
                                    #OPN-{{ String(op.id).padStart(4, '0') }}
                                </td>
                                <td class="px-6 py-4 text-xs font-bold text-slate-700 dark:text-slate-350">
                                    {{ op.outlet?.name }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-600 dark:text-slate-400">
                                    <div class="flex items-center gap-1.5">
                                        <User class="h-3.5 w-3.5 text-slate-400" />
                                        <span>{{ op.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(op.created_at).toLocaleString('id-ID', { dateStyle: 'medium', timeStyle: 'short' }) }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span :class="['px-2.5 py-0.5 border rounded-full text-[9px] font-extrabold uppercase tracking-wider', getStatusBadge(op.status)]">
                                        {{ op.status }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <Link
                                            :href="route('opnames.show', op.id)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-[#8c5a3c] rounded-lg cursor-pointer flex items-center gap-1 text-xs font-bold"
                                        >
                                            <Eye class="h-4 w-4" />
                                            <span>{{ op.status === 'draft' ? 'Lakukan Input' : 'Lihat' }}</span>
                                        </Link>
                                        <button
                                            v-if="op.status === 'draft'"
                                            @click="deleteOpname(op)"
                                            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>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Simple Pagination -->
                <div v-if="opnames.last_page > 1" class="px-6 py-4 border-t border-slate-100 dark:border-slate-800 flex items-center justify-between gap-4">
                    <span class="text-xs text-slate-500">Total {{ opnames.total }} audit opname</span>
                    <div class="flex items-center gap-2">
                        <Link
                            v-for="link in opnames.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">
                <ClipboardList 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 audit stock opname</h3>
                <p class="text-xs text-slate-400 mt-1">Gunakan tombol di atas untuk membuat draf stock opname baru di cabang outlet yang dipilih.</p>
            </div>
        </div>
    </AdminLayout>
</template>
