<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { ArrowLeft, Save, ClipboardList, CheckCircle2 } from 'lucide-vue-next';

interface OpnameItem {
    id: number;
    item_type: 'Ingredient' | 'Product';
    item_id: number;
    name: string;
    system_qty: number;
    actual_qty: number;
    difference_qty: number;
    unit: string;
}

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 };
}

const props = defineProps<{
    opname: OpnameData;
    items: OpnameItem[];
}>();

// Form setup
const form = useForm({
    items: [] as { id: number; actual_qty: number }[]
});

// Load current actual quantities on mount
onMounted(() => {
    form.items = props.items.map(item => ({
        id: item.id,
        actual_qty: item.actual_qty,
    }));
});

// Reactively calculate difference for display
const getDifference = (item: OpnameItem, index: number) => {
    const actual = form.items[index]?.actual_qty ?? 0;
    return Number(actual) - Number(item.system_qty);
};

const submitOpname = () => {
    if (confirm('Apakah Anda yakin ingin menyelesaikan opname ini? Stok sistem akan diperbarui secara permanen.')) {
        form.post(route('opnames.complete', props.opname.id));
    }
};
</script>

<template>
    <Head title="Audit Stock Opname Detail" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Header section -->
            <div class="flex items-center justify-between gap-4">
                <div class="flex items-center gap-3">
                    <Link
                        :href="route('opnames.index')"
                        class="p-2 border border-slate-205 dark:border-slate-800 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 transition-colors"
                    >
                        <ArrowLeft class="h-4 w-4" />
                    </Link>
                    <div>
                        <h1 class="text-xl font-extrabold text-slate-900 dark:text-slate-50 flex items-center gap-2">
                            <span>Audit #OPN-{{ String(opname.id).padStart(4, '0') }}</span>
                            <span :class="[
                                'px-2 py-0.5 border rounded-full text-[9px] font-extrabold uppercase tracking-wider',
                                opname.status === 'draft' ? 'bg-amber-500/10 text-amber-600 border-amber-500/20' : 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20'
                            ]">
                                {{ opname.status }}
                            </span>
                        </h1>
                        <p class="text-xs text-slate-400 mt-1">
                            Outlet: <span class="font-bold text-slate-600 dark:text-slate-300">{{ opname.outlet?.name }}</span> | Oleh: <span class="font-bold text-slate-600 dark:text-slate-300">{{ opname.user?.name }}</span>
                        </p>
                    </div>
                </div>

                <!-- Action Button -->
                <button
                    v-if="opname.status === 'draft'"
                    @click="submitOpname"
                    :disabled="form.processing"
                    class="flex items-center justify-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold rounded-xl transition-all cursor-pointer shadow-lg shadow-emerald-900/10 disabled:opacity-50"
                >
                    <Save class="h-4 w-4" />
                    Selesaikan & Rekonsiliasi
                </button>
            </div>

            <!-- Audit Items Sheet -->
            <div 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">Tipe</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Nama Item</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Stok Sistem</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-center" style="width: 160px;">Stok Fisik Aktif</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider text-right">Selisih</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                            <tr v-for="(item, index) in items" :key="item.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4">
                                    <span v-if="item.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">
                                    <span class="font-extrabold text-xs text-slate-800 dark:text-slate-100">{{ item.name }}</span>
                                </td>
                                <td class="px-6 py-4 text-xs font-bold text-slate-700 dark:text-slate-300 text-right">
                                    {{ item.system_qty }} <span class="text-[10px] text-slate-400 dark:text-slate-500 font-semibold ml-0.5">{{ item.unit }}</span>
                                </td>
                                <td class="px-6 py-4 text-center">
                                    <div class="flex items-center justify-center gap-1.5">
                                        <!-- If draft: allow input -->
                                        <input
                                            v-if="opname.status === 'draft' && form.items[index]"
                                            type="number"
                                            step="0.0001"
                                            v-model="form.items[index].actual_qty"
                                            class="w-24 text-center h-8 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"
                                        />
                                        <!-- If completed: static text -->
                                        <span v-else class="text-xs font-bold text-slate-755 dark:text-slate-200">
                                            {{ item.actual_qty }}
                                        </span>
                                        <span class="text-[10px] text-slate-400 dark:text-slate-500 font-semibold">{{ item.unit }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <span
                                        class="text-xs font-bold animate-in"
                                        :class="[
                                            getDifference(item, index) > 0 ? 'text-emerald-500' : '',
                                            getDifference(item, index) < 0 ? 'text-rose-500' : 'text-slate-400'
                                        ]"
                                    >
                                        {{ getDifference(item, index) > 0 ? '+' : '' }}{{ getDifference(item, index).toFixed(2) }} <span class="text-[10px] text-slate-400 dark:text-slate-500 font-semibold ml-0.5">{{ item.unit }}</span>
                                    </span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
