<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, Percent, ToggleLeft, ToggleRight, X } from 'lucide-vue-next';

interface VoucherData {
    id: number;
    code: string;
    type: 'nominal' | 'percent';
    value: number;
    max_discount: number | null;
    min_purchase: number;
    expires_at: string | null;
    usage_limit: number | null;
    usage_count: number;
    is_active: boolean;
    created_at: string;
}

const props = defineProps<{
    vouchers: VoucherData[];
}>();

// Modal state
const isFormModalOpen = ref(false);
const editingVoucher = ref<VoucherData | null>(null);

// Form config
const form = useForm({
    code: '',
    type: 'percent',
    value: 0,
    max_discount: '',
    min_purchase: 0,
    expires_at: '',
    usage_limit: '',
    is_active: true,
});

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

const openEditModal = (voucher: VoucherData) => {
    editingVoucher.value = voucher;
    form.clearErrors();
    form.code = voucher.code;
    form.type = voucher.type;
    form.value = voucher.value;
    form.max_discount = voucher.max_discount !== null ? String(voucher.max_discount) : '';
    form.min_purchase = voucher.min_purchase;
    form.expires_at = voucher.expires_at ? voucher.expires_at.substring(0, 10) : '';
    form.usage_limit = voucher.usage_limit !== null ? String(voucher.usage_limit) : '';
    form.is_active = voucher.is_active;
    isFormModalOpen.value = true;
};

const submitForm = () => {
    const payload = {
        ...form.data(),
        code: form.code.toUpperCase(),
        max_discount: form.max_discount ? Number(form.max_discount) : null,
        usage_limit: form.usage_limit ? Number(form.usage_limit) : null,
        expires_at: form.expires_at || null,
    };

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

const toggleVoucherStatus = (voucher: VoucherData) => {
    router.put(route('vouchers.update', voucher.id), {
        code: voucher.code,
        type: voucher.type,
        value: voucher.value,
        max_discount: voucher.max_discount,
        min_purchase: voucher.min_purchase,
        expires_at: voucher.expires_at ? voucher.expires_at.substring(0, 10) : null,
        usage_limit: voucher.usage_limit,
        is_active: !voucher.is_active,
    });
};

const deleteVoucher = (voucher: VoucherData) => {
    if (confirm(`Apakah Anda yakin ingin menghapus voucher ${voucher.code}?`)) {
        router.delete(route('vouchers.destroy', voucher.id));
    }
};

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

<template>
    <Head title="Manajemen Voucher" />

    <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">
                        Manajemen Voucher Belanja
                    </h1>
                    <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                        Buat kupon promosi kustom dengan batasan kuota, minimal transaksi, dan masa berlaku.
                    </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 Voucher
                </button>
            </div>

            <!-- Vouchers Table -->
            <div v-if="vouchers.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">Kode Voucher</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">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">Penggunaan</th>
                                <th class="px-6 py-3.5 text-[11px] font-bold text-slate-400 uppercase tracking-wider">Berlaku S/D</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="voucher in vouchers" :key="voucher.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>
                                        <div>
                                            <span class="font-extrabold text-xs text-[#8c5a3c] uppercase block">{{ voucher.code }}</span>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-xs font-semibold text-slate-600 dark:text-slate-400">
                                    <span v-if="voucher.type === 'percent'">Persentase (%)</span>
                                    <span v-else-if="voucher.type === 'nominal'">Nominal (Rp)</span>
                                </td>
                                <td class="px-6 py-4 text-xs font-bold text-slate-800 dark:text-slate-200">
                                    {{ formatValue(voucher) }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-550 dark:text-slate-350">
                                    Rp {{ Number(voucher.min_purchase).toLocaleString('id-ID') }}
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-550 dark:text-slate-350 font-semibold">
                                    {{ voucher.usage_count }} / {{ voucher.usage_limit ? voucher.usage_limit : '∞' }}
                                </td>
                                <td class="px-6 py-4 text-[10px] text-slate-550 dark:text-slate-350">
                                    <div class="flex items-center gap-1">
                                        <Calendar class="h-3 w-3 text-slate-400" />
                                        <span>{{ voucher.expires_at ? voucher.expires_at.substring(0, 10) : 'Selamanya' }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <button
                                        @click="toggleVoucherStatus(voucher)"
                                        class="cursor-pointer transition-colors"
                                    >
                                        <ToggleRight v-if="voucher.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(voucher)"
                                            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="deleteVoucher(voucher)"
                                            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 kupon voucher</h3>
                <p class="text-xs text-slate-400 mt-1">Gunakan tombol di atas untuk membuat voucher 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">
                            {{ editingVoucher ? 'Edit Voucher' : 'Buat Voucher 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">Kode Voucher</label>
                            <input
                                type="text"
                                v-model="form.code"
                                required
                                placeholder="Contoh: MERDEKA50"
                                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] uppercase"
                            />
                        </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 Potongan</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>
                                </select>
                            </div>
                            <div>
                                <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-500 uppercase tracking-wider mb-1.5">Nilai Diskon</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 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">Maks. Potongan (Rp)</label>
                                <input
                                    type="number"
                                    v-model="form.max_discount"
                                    placeholder="Tidak terbatas"
                                    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-550 uppercase tracking-wider mb-1.5">Min. Belanja (Rp)</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>

                        <div>
                            <label class="block text-[11px] font-bold text-slate-450 dark:text-slate-550 uppercase tracking-wider mb-1.5">Tanggal Kadaluarsa</label>
                            <input
                                type="date"
                                v-model="form.expires_at"
                                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">Kuota Limit</label>
                                <input
                                    type="number"
                                    v-model="form.usage_limit"
                                    placeholder="Tidak terbatas"
                                    min="1"
                                    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">Status Aktif</label>
                                <select
                                    v-model="form.is_active"
                                    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="true">Aktif</option>
                                    <option :value="false">Tidak Aktif</option>
                                </select>
                            </div>
                        </div>

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