<script setup>
import { computed, reactive, ref } from 'vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import AppModal from '@/Components/ui/AppModal.vue';
import AppTable from '@/Components/ui/AppTable.vue';
import AppTabs from '@/Components/ui/AppTabs.vue';

const props = defineProps({
    coupons: { type: Object, required: true },
    filters: { type: Object, default: () => ({}) },
    statuses: { type: Array, default: () => ['active', 'inactive'] },
    types: { type: Array, default: () => ['fixed', 'percent'] },
    tiers: { type: Array, default: () => ['subscriber', 'reseller', 'agent'] },
    categories: { type: Array, default: () => [] },
    networks: { type: Array, default: () => [] },
    summary: { type: Object, default: () => ({}) },
});

const filters = reactive({
    q: props.filters?.q || '',
    status: props.filters?.status || '',
});

const modalOpen = ref(false);
const editingId = ref(null);
const activeTab = ref('manage');

const form = useForm({
    name: '',
    code: '',
    status: 'active',
    type: 'fixed',
    value: '',
    min_amount: '',
    max_discount: '',
    usage_limit: '',
    per_user_limit: '',
    is_stackable: false,
    applicable_category_ids: [],
    applicable_network_ids: [],
    applicable_customer_tiers: [],
    starts_at: '',
    ends_at: '',
});

const isEditing = computed(() => editingId.value !== null);

const openCreate = () => {
    editingId.value = null;
    form.reset();
    form.clearErrors();
    form.status = 'active';
    form.type = 'fixed';
    form.is_stackable = false;
    form.applicable_category_ids = [];
    form.applicable_network_ids = [];
    form.applicable_customer_tiers = [];
    modalOpen.value = true;
};

const openEdit = (coupon) => {
    editingId.value = coupon.id;
    form.clearErrors();
    form.name = coupon.name || '';
    form.code = coupon.code || '';
    form.status = coupon.status || 'active';
    form.type = coupon.type || 'fixed';
    form.value = coupon.value ?? '';
    form.min_amount = coupon.min_amount ?? '';
    form.max_discount = coupon.max_discount ?? '';
    form.usage_limit = coupon.usage_limit ?? '';
    form.per_user_limit = coupon.per_user_limit ?? '';
    form.is_stackable = !!coupon.is_stackable;
    form.applicable_category_ids = (coupon.applicable_category_ids || []).map((v) => Number(v));
    form.applicable_network_ids = (coupon.applicable_network_ids || []).map((v) => Number(v));
    form.applicable_customer_tiers = [...(coupon.applicable_customer_tiers || [])];
    form.starts_at = coupon.starts_at || '';
    form.ends_at = coupon.ends_at || '';
    modalOpen.value = true;
};

const closeModal = () => {
    if (form.processing) return;
    modalOpen.value = false;
};

const submit = () => {
    const payload = {
        ...form.data(),
        code: String(form.code || '').trim().toUpperCase(),
        min_amount: form.min_amount === '' ? null : form.min_amount,
        max_discount: form.max_discount === '' ? null : form.max_discount,
        usage_limit: form.usage_limit === '' ? null : form.usage_limit,
        per_user_limit: form.per_user_limit === '' ? null : form.per_user_limit,
        starts_at: form.starts_at || null,
        ends_at: form.ends_at || null,
    };

    if (isEditing.value) {
        form.transform(() => payload).put(route('admin.coupons.update', editingId.value), {
            preserveScroll: true,
            onSuccess: () => closeModal(),
        });
        return;
    }

    form.transform(() => payload).post(route('admin.coupons.store'), {
        preserveScroll: true,
        onSuccess: () => closeModal(),
    });
};

const applyFilters = () => {
    router.get(route('admin.coupons.index'), {
        q: filters.q || undefined,
        status: filters.status || undefined,
    }, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
    });
};

const clearFilters = () => {
    filters.q = '';
    filters.status = '';
    applyFilters();
};

const toggleSelection = (field, value) => {
    const normalized = Number.isFinite(Number(value)) ? Number(value) : value;
    const current = Array.isArray(form[field]) ? [...form[field]] : [];
    const exists = current.some((item) => String(item) === String(normalized));
    form[field] = exists
        ? current.filter((item) => String(item) !== String(normalized))
        : [...current, normalized];
};

const selectionHas = (field, value) => (form[field] || []).some((item) => String(item) === String(value));

const formatCurrency = (value) => {
    const n = Number(value || 0);
    if (Number.isNaN(n)) return 'NGN 0.00';
    return `NGN ${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

const couponValueLabel = (coupon) => coupon.type === 'percent'
    ? `${Number(coupon.value).toFixed(2)}%`
    : formatCurrency(coupon.value);

const statusChipClass = (status) => ({
    active: 'bg-emerald-50 text-emerald-700 ring-emerald-200',
    inactive: 'bg-slate-100 text-slate-700 ring-slate-200',
}[status] || 'bg-slate-100 text-slate-700 ring-slate-200');

const pageTabs = computed(() => ([
    { key: 'manage', label: 'Manage Coupons', count: props.coupons?.total ?? props.coupons?.data?.length ?? 0 },
    { key: 'overview', label: 'Overview' },
]));
</script>

<template>
    <Head title="Coupons" />

    <AdminLayout>
        <template #header>
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h2 class="text-xl font-semibold text-slate-900">Coupons</h2>
                    <p class="mt-1 text-sm text-slate-500">Create discount codes for data, airtime, cable, electricity, and exam pins.</p>
                </div>
                <button
                    type="button"
                    class="inline-flex items-center justify-center rounded-lg border border-slate-900 bg-slate-900 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800"
                    @click="openCreate"
                >
                    + New Coupon
                </button>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-5 px-4 py-6 sm:px-6 lg:px-8">
            <AppTabs v-model="activeTab" :tabs="pageTabs" aria-label="Coupon sections" />

            <div v-if="activeTab === 'overview'" class="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
                <AppCard title="Coupons" :subtitle="String(summary?.total ?? 0)" />
                <AppCard title="Active" :subtitle="String(summary?.active ?? 0)" />
                <AppCard title="Inactive" :subtitle="String(summary?.inactive ?? 0)" />
                <AppCard title="Applied Uses" :subtitle="String(summary?.applied_redemptions ?? 0)" />
                <AppCard title="Discount Given" :subtitle="formatCurrency(summary?.total_discount ?? 0)" />
            </div>

            <AppCard v-if="activeTab === 'manage'" title="Filter Coupons" subtitle="Search by name/code or filter by status.">
                <div class="grid gap-3 md:grid-cols-[1fr_220px_auto_auto]">
                    <input
                        v-model="filters.q"
                        type="text"
                        placeholder="Search name or code"
                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0"
                        @keyup.enter="applyFilters"
                    />
                    <select
                        v-model="filters.status"
                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0"
                    >
                        <option value="">All statuses</option>
                        <option v-for="status in statuses" :key="status" :value="status">
                            {{ status }}
                        </option>
                    </select>
                    <button
                        type="button"
                        class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        @click="applyFilters"
                    >
                        Apply
                    </button>
                    <button
                        type="button"
                        class="rounded-lg border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100"
                        @click="clearFilters"
                    >
                        Clear
                    </button>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'manage'" title="Coupon List" subtitle="Manage coupon rules and targeting.">
                <AppTable>
                    <thead class="bg-slate-50">
                        <tr class="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                            <th class="px-4 py-3">Code</th>
                            <th class="px-4 py-3">Details</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Usage</th>
                            <th class="px-4 py-3">Window</th>
                            <th class="px-4 py-3"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm">
                        <tr v-for="coupon in coupons.data" :key="coupon.id">
                            <td class="px-4 py-3 align-top">
                                <div class="font-semibold uppercase text-slate-900">{{ coupon.code }}</div>
                                <div class="mt-1 text-xs text-slate-500">{{ couponValueLabel(coupon) }}</div>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="font-medium text-slate-900">{{ coupon.name }}</div>
                                <div class="mt-1 space-y-0.5 text-xs text-slate-500">
                                    <div>Type: {{ coupon.type }}</div>
                                    <div v-if="coupon.min_amount !== null">Min: {{ formatCurrency(coupon.min_amount) }}</div>
                                    <div v-if="coupon.max_discount !== null">Max discount: {{ formatCurrency(coupon.max_discount) }}</div>
                                    <div v-if="(coupon.applicable_customer_tiers || []).length">
                                        Tiers: {{ coupon.applicable_customer_tiers.join(', ') }}
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset" :class="statusChipClass(coupon.status)">
                                    {{ coupon.status }}
                                </span>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="text-xs text-slate-600">
                                    <div>Active uses: {{ coupon.active_usage_count }}</div>
                                    <div>Applied: {{ coupon.applied_usage_count }}</div>
                                    <div v-if="coupon.usage_limit">Limit: {{ coupon.usage_limit }}</div>
                                    <div v-if="coupon.per_user_limit">Per user: {{ coupon.per_user_limit }}</div>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="text-xs text-slate-600">
                                    <div>Start: {{ coupon.starts_at || '-' }}</div>
                                    <div>End: {{ coupon.ends_at || '-' }}</div>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="flex justify-end">
                                    <button
                                        type="button"
                                        class="rounded-md border border-slate-300 px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                        @click="openEdit(coupon)"
                                    >
                                        Edit
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="!coupons.data?.length">
                            <td colspan="6" class="px-4 py-8 text-center text-sm text-slate-500">No coupons found.</td>
                        </tr>
                    </tbody>
                </AppTable>

                <div v-if="coupons.links?.length" class="mt-4 flex flex-wrap gap-2">
                    <button
                        v-for="link in coupons.links"
                        :key="link.label"
                        type="button"
                        class="rounded-md border px-3 py-1.5 text-xs font-semibold"
                        :class="link.active ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-50'"
                        :disabled="!link.url"
                        @click="link.url && router.visit(link.url, { preserveScroll: true, preserveState: true })"
                        v-html="link.label"
                    />
                </div>
            </AppCard>
        </div>

        <AppModal :show="modalOpen" :title="isEditing ? 'Edit Coupon' : 'Create Coupon'" @close="closeModal">
            <div class="max-h-[75vh] space-y-4 overflow-y-auto pr-1">
                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Coupon Name</label>
                        <input v-model="form.name" type="text" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Weekend Data Promo" />
                        <p v-if="form.errors.name" class="mt-1 text-xs text-rose-600">{{ form.errors.name }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Code</label>
                        <input v-model="form.code" type="text" maxlength="64" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm uppercase shadow-sm focus:border-slate-400 focus:ring-0" placeholder="SAVE100" />
                        <p v-if="form.errors.code" class="mt-1 text-xs text-rose-600">{{ form.errors.code }}</p>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Status</label>
                        <select v-model="form.status" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0">
                            <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                        </select>
                        <p v-if="form.errors.status" class="mt-1 text-xs text-rose-600">{{ form.errors.status }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Type</label>
                        <select v-model="form.type" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0">
                            <option value="fixed">Fixed (NGN)</option>
                            <option value="percent">Percent (%)</option>
                        </select>
                        <p v-if="form.errors.type" class="mt-1 text-xs text-rose-600">{{ form.errors.type }}</p>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Value</label>
                        <input v-model="form.value" type="number" min="0.01" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                        <p v-if="form.errors.value" class="mt-1 text-xs text-rose-600">{{ form.errors.value }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Min Amount</label>
                        <input v-model="form.min_amount" type="number" min="0" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="form.errors.min_amount" class="mt-1 text-xs text-rose-600">{{ form.errors.min_amount }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Max Discount</label>
                        <input v-model="form.max_discount" type="number" min="0" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="form.errors.max_discount" class="mt-1 text-xs text-rose-600">{{ form.errors.max_discount }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Per User Limit</label>
                        <input v-model="form.per_user_limit" type="number" min="1" step="1" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="form.errors.per_user_limit" class="mt-1 text-xs text-rose-600">{{ form.errors.per_user_limit }}</p>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Total Usage Limit</label>
                        <input v-model="form.usage_limit" type="number" min="1" step="1" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="form.errors.usage_limit" class="mt-1 text-xs text-rose-600">{{ form.errors.usage_limit }}</p>
                    </div>
                    <div class="flex items-end">
                        <label class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                            <input v-model="form.is_stackable" type="checkbox" class="rounded border-slate-300 text-slate-900 focus:ring-slate-400" />
                            Allow stacking (future use)
                        </label>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Starts At</label>
                        <input v-model="form.starts_at" type="datetime-local" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                        <p v-if="form.errors.starts_at" class="mt-1 text-xs text-rose-600">{{ form.errors.starts_at }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Ends At</label>
                        <input v-model="form.ends_at" type="datetime-local" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                        <p v-if="form.errors.ends_at" class="mt-1 text-xs text-rose-600">{{ form.errors.ends_at }}</p>
                    </div>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Customer Tiers (optional)</div>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="tier in tiers"
                            :key="tier"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold capitalize"
                            :class="selectionHas('applicable_customer_tiers', tier)
                                ? 'border-slate-900 bg-slate-900 text-white'
                                : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_customer_tiers', tier)"
                        >
                            {{ tier }}
                        </button>
                    </div>
                    <p v-if="form.errors.applicable_customer_tiers" class="mt-2 text-xs text-rose-600">{{ form.errors.applicable_customer_tiers }}</p>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Categories (optional)</div>
                    <p class="mt-1 text-xs text-slate-500">Leave empty to allow all services.</p>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="category in categories"
                            :key="category.id"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold"
                            :class="selectionHas('applicable_category_ids', category.id)
                                ? 'border-slate-900 bg-slate-900 text-white'
                                : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_category_ids', category.id)"
                        >
                            {{ category.name }}
                        </button>
                    </div>
                    <p v-if="form.errors.applicable_category_ids" class="mt-2 text-xs text-rose-600">{{ form.errors.applicable_category_ids }}</p>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Networks (optional)</div>
                    <p class="mt-1 text-xs text-slate-500">Useful for data/airtime plans. Leave empty to allow all networks.</p>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="network in networks"
                            :key="network.id"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold"
                            :class="selectionHas('applicable_network_ids', network.id)
                                ? 'border-slate-900 bg-slate-900 text-white'
                                : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_network_ids', network.id)"
                        >
                            {{ network.name }}
                        </button>
                    </div>
                    <p v-if="form.errors.applicable_network_ids" class="mt-2 text-xs text-rose-600">{{ form.errors.applicable_network_ids }}</p>
                </div>

                <div class="flex items-center justify-end gap-2 pt-1">
                    <button
                        type="button"
                        class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        :disabled="form.processing"
                        @click="closeModal"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        class="rounded-lg border border-slate-900 bg-slate-900 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800 disabled:opacity-60"
                        :disabled="form.processing"
                        @click="submit"
                    >
                        {{ form.processing ? 'Saving...' : (isEditing ? 'Update Coupon' : 'Create Coupon') }}
                    </button>
                </div>
            </div>
        </AppModal>
    </AdminLayout>
</template>
