<script setup lang="ts">
import { destroy, store, update } from '@/actions/App/Http/Controllers/Admin/BonusController';
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Link, router, useForm } from '@inertiajs/vue3';
import { Gift, Pencil, PlusCircle, Trash2, X } from 'lucide-vue-next';
import { ref } from 'vue';

defineOptions({ layout: AdminLayout });

const props = defineProps<{
    bonuses: Array<{
        id: number;
        name: string;
        amount_type: 'fixed' | 'percentage';
        amount: string;
        eligibility_type: Record<string, any> | null;
        generations_count: number;
    }>;
}>();

const showForm = ref(false);
const editing = ref<number | null>(null);

const form = useForm({
    name: '',
    amount_type: 'fixed' as 'fixed' | 'percentage',
    amount: '',
    eligibility_type: {
        gender: [] as string[],
        religion: [] as string[],
        min_service_months: null as number | null,
    } as any,
});

const genderOptions = ['male', 'female', 'other'];
const religionOptions = ['islam', 'hinduism', 'christianity', 'buddhism', 'other'];

function toggleFilter(field: 'gender' | 'religion', value: string) {
    const arr: string[] = form.eligibility_type[field] ?? [];
    const idx = arr.indexOf(value);
    if (idx === -1) {
        arr.push(value);
    } else {
        arr.splice(idx, 1);
    }
    form.eligibility_type[field] = arr;
}

function isSelected(field: 'gender' | 'religion', value: string): boolean {
    return (form.eligibility_type[field] ?? []).includes(value);
}

function openCreate() {
    editing.value = null;
    form.reset();
    form.eligibility_type = { gender: [], religion: [], min_service_months: null };
    showForm.value = true;
}

function openEdit(b: (typeof props.bonuses)[0]) {
    editing.value = b.id;
    form.name = b.name;
    form.amount_type = b.amount_type;
    form.amount = b.amount;
    const et = b.eligibility_type ?? {};
    form.eligibility_type = {
        gender: et.gender ?? [],
        religion: et.religion ?? [],
        min_service_months: et.min_service_months ?? null,
    };
    showForm.value = true;
}

function submit() {
    const url = editing.value ? update({ bonus: editing.value }).url : store().url;
    const method = editing.value ? 'put' : 'post';
    form[method](url, {
        preserveScroll: true,
        onSuccess: () => {
            showForm.value = false;
            form.reset();
        },
    });
}

const confirmState = ref({
    show: false,
    id: 0,
    processing: false,
});

function deleteBonus(id: number) {
    confirmState.value.id = id;
    confirmState.value.show = true;
}

function executeDelete() {
    confirmState.value.processing = true;
    router.delete(destroy({ bonus: confirmState.value.id }).url, {
        preserveScroll: true,
        onFinish: () => {
            confirmState.value.show = false;
            confirmState.value.processing = false;
        },
    });
}
</script>

<template>
    <div class="space-y-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-xl font-extrabold text-slate-800 dark:text-white">Bonuses</h1>
                <p class="text-sm text-slate-500">Define bonus types, amounts, and eligibility rules</p>
            </div>
            <div class="flex gap-3">
                <Link
                    href="/admin/bonuses/generate"
                    class="flex items-center gap-2 rounded-xl border border-indigo-200 bg-indigo-50 px-4 py-2 text-sm font-bold text-indigo-700 transition-all hover:bg-indigo-100"
                >
                    <Gift class="h-4 w-4" /> Generate Bonus
                </Link>
                <button
                    @click="openCreate"
                    class="flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-bold text-white shadow-2xl shadow-indigo-900/30 transition-all hover:bg-indigo-700 active:scale-95"
                >
                    <PlusCircle class="h-4 w-4" /> New Bonus
                </button>
            </div>
        </div>

        <!-- Slide-over -->
        <Teleport to="body">
            <!-- Backdrop -->
            <Transition
                enter-active-class="transition-opacity ease-linear duration-300"
                enter-from-class="opacity-0"
                enter-to-class="opacity-100"
                leave-active-class="transition-opacity ease-linear duration-200"
                leave-from-class="opacity-100"
                leave-to-class="opacity-0"
            >
                <div v-if="showForm" class="fixed inset-0 z-[9999] bg-black/30 backdrop-blur-sm" @click="showForm = false" />
            </Transition>

            <!-- Slide-over Panel -->
            <Transition
                enter-active-class="transition ease-in-out duration-300 transform"
                enter-from-class="translate-x-full"
                enter-to-class="translate-x-0"
                leave-active-class="transition ease-in-out duration-200 transform"
                leave-from-class="translate-x-0"
                leave-to-class="translate-x-full"
            >
                <div
                    v-if="showForm"
                    class="fixed inset-y-0 right-0 z-[10000] flex h-screen w-full max-w-md flex-col bg-white shadow-2xl dark:bg-slate-900"
                >
                    <div class="flex items-center justify-between border-b border-slate-200 p-5 dark:border-slate-700">
                        <h2 class="text-base font-bold text-slate-800 dark:text-white">{{ editing ? 'Edit' : 'New' }} Bonus</h2>
                        <button @click="showForm = false"><X class="h-5 w-5 text-slate-400" /></button>
                    </div>
                    <div class="flex-1 space-y-5 overflow-y-auto p-5">
                        <!-- Name -->
                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Bonus Name</label>
                            <input
                                v-model="form.name"
                                type="text"
                                placeholder="e.g. Eid Bonus, Festival Bonus"
                                class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                            />
                            <p v-if="form.errors.name" class="mt-1 text-xs text-red-500">{{ form.errors.name }}</p>
                        </div>

                        <!-- Amount -->
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Amount Type</label>
                                <select
                                    v-model="form.amount_type"
                                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                                >
                                    <option value="fixed">Fixed Amount</option>
                                    <option value="percentage">% of Gross</option>
                                </select>
                            </div>
                            <div>
                                <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">
                                    {{ form.amount_type === 'percentage' ? 'Percentage (%)' : 'Amount' }}
                                </label>
                                <input
                                    v-model="form.amount"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                                />
                                <p v-if="form.errors.amount" class="mt-1 text-xs text-red-500">{{ form.errors.amount }}</p>
                            </div>
                        </div>

                        <!-- Divider -->
                        <div class="border-t border-slate-100 pt-3 dark:border-slate-800">
                            <p class="mb-3 text-xs font-bold tracking-widest text-slate-400 uppercase">Eligibility Filters</p>
                            <p class="mb-4 text-xs text-slate-500">Leave all unchecked to apply to all employees.</p>
                        </div>

                        <!-- Gender -->
                        <div>
                            <label class="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">Gender</label>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    v-for="g in genderOptions"
                                    :key="g"
                                    type="button"
                                    @click="toggleFilter('gender', g)"
                                    class="rounded-full border px-3 py-1 text-xs font-semibold capitalize transition-all"
                                    :class="
                                        isSelected('gender', g)
                                            ? 'border-indigo-500 bg-indigo-600 text-white'
                                            : 'border-slate-300 bg-white text-slate-600 hover:border-indigo-300 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300'
                                    "
                                >
                                    {{ g }}
                                </button>
                            </div>
                        </div>

                        <!-- Religion -->
                        <div>
                            <label class="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">Religion</label>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    v-for="r in religionOptions"
                                    :key="r"
                                    type="button"
                                    @click="toggleFilter('religion', r)"
                                    class="rounded-full border px-3 py-1 text-xs font-semibold capitalize transition-all"
                                    :class="
                                        isSelected('religion', r)
                                            ? 'border-violet-500 bg-violet-600 text-white'
                                            : 'border-slate-300 bg-white text-slate-600 hover:border-violet-300 dark:border-slate-600 dark:bg-slate-800 dark:text-slate-300'
                                    "
                                >
                                    {{ r }}
                                </button>
                            </div>
                        </div>

                        <!-- Min Service -->
                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300"> Minimum Service (months) </label>
                            <input
                                v-model="form.eligibility_type.min_service_months"
                                type="number"
                                min="0"
                                placeholder="Leave blank = no restriction"
                                class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                            />
                        </div>
                    </div>
                    <div class="flex gap-3 border-t border-slate-200 p-5 dark:border-slate-700">
                        <button
                            @click="showForm = false"
                            class="flex-1 rounded-xl bg-slate-100 px-4 py-2 text-sm font-bold text-slate-600 dark:bg-slate-800"
                        >
                            Cancel
                        </button>
                        <button
                            @click="submit"
                            :disabled="form.processing"
                            class="flex-1 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-black tracking-widest text-white uppercase shadow-2xl shadow-indigo-900/30 transition-all hover:bg-indigo-700 active:scale-95 disabled:opacity-50"
                        >
                            {{ form.processing ? 'Saving…' : 'Save' }}
                        </button>
                    </div>
                </div>
            </Transition>
        </Teleport>

        <!-- Table -->
        <div class="overflow-hidden rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200 dark:border-slate-700">
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Name</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Type</th>
                        <th class="px-5 py-3 text-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Amount</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Eligibility</th>
                        <th class="px-5 py-3 text-center text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Generations</th>
                        <th class="px-5 py-3" />
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="b in bonuses"
                        :key="b.id"
                        class="border-b border-slate-100 transition-colors hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-800/50"
                    >
                        <td class="px-5 py-3 font-medium text-slate-800 dark:text-white">{{ b.name }}</td>
                        <td class="px-5 py-3 text-sm text-slate-500 capitalize">{{ b.amount_type }}</td>
                        <td class="px-5 py-3 text-right font-mono text-slate-700 dark:text-slate-300">
                            {{ b.amount_type === 'percentage' ? b.amount + '%' : parseFloat(b.amount).toLocaleString() }}
                        </td>
                        <td class="px-5 py-3">
                            <div class="flex flex-wrap gap-1">
                                <template v-if="b.eligibility_type?.gender?.length">
                                    <span
                                        v-for="g in b.eligibility_type.gender"
                                        :key="g"
                                        class="rounded-full bg-indigo-50 px-2 py-0.5 text-[10px] font-semibold text-indigo-700 capitalize"
                                        >{{ g }}</span
                                    >
                                </template>
                                <template v-if="b.eligibility_type?.religion?.length">
                                    <span
                                        v-for="r in b.eligibility_type.religion"
                                        :key="r"
                                        class="rounded-full bg-violet-50 px-2 py-0.5 text-[10px] font-semibold text-violet-700 capitalize"
                                        >{{ r }}</span
                                    >
                                </template>
                                <span
                                    v-if="b.eligibility_type?.min_service_months"
                                    class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-semibold text-amber-700"
                                >
                                    {{ b.eligibility_type.min_service_months }}m+ service
                                </span>
                                <span
                                    v-if="
                                        !b.eligibility_type?.gender?.length &&
                                        !b.eligibility_type?.religion?.length &&
                                        !b.eligibility_type?.min_service_months
                                    "
                                    class="text-xs text-slate-400"
                                    >All employees</span
                                >
                            </div>
                        </td>
                        <td class="px-5 py-3 text-center">
                            <span
                                class="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-600 dark:bg-slate-700 dark:text-slate-400"
                            >
                                {{ b.generations_count }}
                            </span>
                        </td>
                        <td class="px-5 py-3">
                            <div class="flex items-center justify-end gap-2">
                                <button @click="openEdit(b)" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-700">
                                    <Pencil class="h-4 w-4 text-slate-500" />
                                </button>
                                <button
                                    @click="deleteBonus(b.id)"
                                    class="rounded-lg p-1.5 transition-colors hover:bg-red-50 dark:hover:bg-red-900/20"
                                >
                                    <Trash2 class="h-4 w-4 text-red-500" />
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="!bonuses.length">
                        <td colspan="6" class="px-5 py-10 text-center text-sm text-slate-400">No bonuses defined yet.</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <ConfirmationModal
            :show="confirmState.show"
            title="Delete Bonus"
            message="Are you sure you want to delete this bonus? This action cannot be undone."
            type="danger"
            confirm-text="Delete"
            :processing="confirmState.processing"
            @close="confirmState.show = false"
            @confirm="executeDelete"
        />
    </div>
</template>
