<script setup lang="ts">
import { ref } from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Tag, Plus, Edit2, Trash2, Calendar, ShoppingBag, ToggleLeft, ToggleRight, X } from 'lucide-vue-next';

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

interface PromoData {
    id: number;
    name: string;
    type: 'percent' | 'nominal' | 'bogo';
    value: number;
    min_purchase: number;
    product_id: number | null;
    product?: Product | null;
    is_active: boolean;
    created_at: string;
}

const props = defineProps<{
    promos: PromoData[];
    products: Product[];
}>();

// Modal state
const isFormModalOpen = ref(false);
const editingPromo = ref<PromoData | null>(null);

// Form config
const form = useForm({
    name: '',
    type: 'percent',
    value: 0,
    min_purchase: 0,
    product_id: '',
    is_active: true,
});

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

const openEditModal = (promo: PromoData) => {
    editingPromo.value = promo;
    form.clearErrors();
    form.name = promo.name;
    form.type = promo.type;
    form.value = promo.value;
    form.min_purchase = promo.min_purchase;
    form.product_id = promo.product_id ? String(promo.product_id) : '';
    form.is_active = promo.is_active;
    isFormModalOpen.value = true;
};

const submitForm = () => {
    // Sanitize product_id
    const payload = {
        ...form.data(),
        product_id: form.product_id ? Number(form.product_id) : null,
    };

    if (editingPromo.value) {
        router.put(route('promos.update', editingPromo.value.id), payload, {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    } else {
        router.post(route('promos.store'), payload, {
            onSuccess: () => {
                isFormModalOpen.value = false;
                form.reset();
            },
        });
    }
};

const togglePromoStatus = (promo: PromoData) => {
    router.put(route('promos.update', promo.id), {
        name: promo.name,
        type: promo.type,
        value: promo.value,
        min_purchase: promo.min_purchase,
        product_id: promo.product_id,
        is_active: !promo.is_active,
    });
};

const deletePromo = (promo: PromoData) => {
    if (confirm(`Apakah Anda yakin ingin menghapus promo ${promo.name}?`)) {
        router.delete(route('promos.destroy', promo.id));
    }
};

const formatValue = (promo: PromoData) => {
    if (promo.type === 'percent') {
        return `${Number(promo.value)}%`;
    }
    return `Rp ${Number(promo.value).toLocaleString('id-ID')}`;
};
</script>

<template>
    <Head title="Promo Engine" />

    <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">
                        Promo Engine
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Buat dan atur program diskon nominal, persentase belanja, atau Buy One Get One (BOGO).
                    </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" />
                    Tambah Promo
                </button>
            </div>

            <!-- Promos Table -->
            <div v-if="promos.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">Nama Promo</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Tipe Promo</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Nilai Potongan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Min. Belanja</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Berlaku Produk</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Status Aktif</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="promo in promos" :key="promo.id" class="hover:bg-slate-50/30 dark:hover:bg-slate-800/10">
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-2.5">
                                        <div class="h-8 w-8 rounded-xl bg-[#8c5a3c]/10 text-[#8c5a3c] flex items-center justify-center">
                                            <Tag class="h-4 w-4" />
                                        </div>
                                        <span class="font-extrabold text-xs text-slate-850 dark:text-slate-100">{{ promo.name }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-xs font-semibold text-slate-600 dark:text-slate-400">
                                    <span v-if="promo.type === 'percent'">Persentase (%)</span>
                                    <span v-else-if="promo.type === 'nominal'">Nominal (Rp)</span>
                                    <span v-else-if="promo.type === 'bogo'">BOGO (Buy 1 Get 1)</span>
                                </td>
                                <td class="px-6 py-4 text-xs font-bold text-slate-800 dark:text-slate-200">
                                    {{ formatValue(promo) }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-550 dark:text-slate-350">
                                    Rp {{ Number(promo.min_purchase).toLocaleString('id-ID') }}
                                </td>
                                <td class="px-6 py-4">
                                    <div v-if="promo.product" class="flex items-center gap-1.5 text-xs text-slate-600 dark:text-slate-400">
                                        <ShoppingBag class="h-3.5 w-3.5 text-[#8c5a3c]" />
                                        <span>{{ promo.product.name }}</span>
                                    </div>
                                    <span v-else class="text-xs text-slate-400 italic">Semua Produk</span>
                                </td>
                                <td class="px-6 py-4">
                                    <button
                                        @click="togglePromoStatus(promo)"
                                        class="cursor-pointer transition-colors"
                                    >
                                        <ToggleRight v-if="promo.is_active" class="h-6 w-6 text-[#8c5a3c]" />
                                        <ToggleLeft v-else class="h-6 w-6 text-slate-300 dark:text-slate-600" />
                                    </button>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <button
                                            @click="openEditModal(promo)"
                                            class="p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 hover:text-slate-800 dark:hover:text-slate-200 rounded-lg cursor-pointer"
                                        >
                                            <Edit2 class="h-3.5 w-3.5" />
                                        </button>
                                        <button
                                            @click="deletePromo(promo)"
                                            class="p-1.5 hover:bg-slate-105 dark:hover:bg-slate-800 text-slate-550 hover:text-rose-600 rounded-lg cursor-pointer"
                                        >
                                            <Trash2 class="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </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">
                <Tag class="h-10 w-10 text-slate-350 dark:text-slate-600 mx-auto mb-3" />
                <h3 class="text-sm font-bold text-slate-800 dark:text-slate-200">Belum ada promo</h3>
                <p class="text-xs text-slate-400 mt-1">Gunakan tombol di atas untuk membuat promosi diskon pertama Anda.</p>
            </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="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">
                            {{ editingPromo ? 'Edit Program Promo' : 'Buat Program Promo Baru' }}
                        </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">Nama Kampanye Promo</label>
                            <input
                                type="text"
                                v-model="form.name"
                                required
                                placeholder="Contoh: Diskon Kopi Akhir Pekan"
                                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]"
                            />
                        </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 Promo</label>
                                <select
                                    v-model="form.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="percent">Persentase (%)</option>
                                    <option value="nominal">Nominal (Rp)</option>
                                    <option value="bogo">BOGO (Buy 1 Get 1)</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nilai Potongan</label>
                                <input
                                    type="number"
                                    v-model="form.value"
                                    required
                                    min="0"
                                    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]"
                                />
                            </div>
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Minimal Pembelian (Rupiah)</label>
                            <input
                                type="number"
                                v-model="form.min_purchase"
                                required
                                min="0"
                                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]"
                            />
                        </div>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Berlaku Khusus Produk (Opsional)</label>
                            <select
                                v-model="form.product_id"
                                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="">Semua menu / produk</option>
                                <option v-for="p in products" :key="p.id" :value="String(p.id)">{{ p.name }}</option>
                            </select>
                        </div>

                        <div class="flex items-center justify-between border-t border-slate-100 dark:border-slate-800 pt-4 mt-2">
                            <div>
                                <span class="block text-xs font-extrabold text-slate-800 dark:text-slate-200">Aktifkan Langsung</span>
                                <span class="block text-[10px] text-slate-450 mt-0.5">Promo ini akan otomatis dapat dihitung/diterapkan di POS cashier.</span>
                            </div>
                            <input
                                type="checkbox"
                                v-model="form.is_active"
                                class="h-4.5 w-4.5 accent-[#8c5a3c] rounded cursor-pointer"
                            />
                        </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>
