<script setup lang="ts">
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { router, useForm } from '@inertiajs/vue3';
import { CheckCircle, ChevronLeft, Gift, Users } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';

defineOptions({ layout: AdminLayout });

const props = defineProps<{
    bonuses: Array<{ id: number; name: string; amount_type: string; amount: string }>;
    bonus?: { id: number; name: string; amount_type: string; amount: string };
    month?: string;
    eligibleEmployees?: Array<{
        id: number;
        name: string;
        job_title: string | null;
        department: string | null;
        gross_salary: number;
        calculated_bonus: number;
    }>;
    existingGeneration?: {
        id: number;
        status: string;
        items: Array<{ employee_id: number }>;
    } | null;
}>();

const isLocked = computed(() => !!props.existingGeneration && props.existingGeneration.status !== 'draft');

// ── Setup form ────────────────────────────────────────────────────────────────
const selectedBonusId = ref<number | null>(props.bonus?.id ?? null);
const selectedMonth = ref(props.month ?? new Date().toISOString().slice(0, 7));

function loadPreview() {
    if (!selectedBonusId.value) return;
    router.get('/admin/bonuses/generate/preview', { bonus_id: selectedBonusId.value, month: selectedMonth.value }, { preserveScroll: true });
}

// ── Formatting ────────────────────────────────────────────────────────────────
function fmt(n: number) {
    return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

// ── Search & Filter ───────────────────────────────────────────────────────────
const searchQuery = ref('');

const filteredEmployees = computed(() => {
    if (!props.eligibleEmployees) return [];
    if (!searchQuery.value) return props.eligibleEmployees;

    const term = searchQuery.value.toLowerCase();
    return props.eligibleEmployees.filter((e) => {
        return (
            e.name.toLowerCase().includes(term) ||
            (e.job_title && e.job_title.toLowerCase().includes(term)) ||
            (e.department && e.department.toLowerCase().includes(term))
        );
    });
});

// ── Row selection ─────────────────────────────────────────────────────────────
const selectedIds = ref<Set<number>>(new Set());

// Pre-select all when employees load (only once)
watch(
    () => props.eligibleEmployees,
    (list) => {
        if (list) {
            if (props.existingGeneration && props.existingGeneration.items) {
                const existingIds = props.existingGeneration.items.map((i: any) => i.employee_id);
                selectedIds.value = new Set(existingIds);
            } else {
                selectedIds.value = new Set(list.map((e) => e.id));
            }
        }
    },
    { immediate: true },
);

const allSelected = computed(() => filteredEmployees.value.length > 0 && filteredEmployees.value.every((e) => selectedIds.value.has(e.id)));

const someSelected = computed(() => filteredEmployees.value.some((e) => selectedIds.value.has(e.id)) && !allSelected.value);

function toggleAll() {
    if (isLocked.value) return;
    const next = new Set(selectedIds.value);
    if (allSelected.value) {
        filteredEmployees.value.forEach((e) => next.delete(e.id));
    } else {
        filteredEmployees.value.forEach((e) => next.add(e.id));
    }
    selectedIds.value = next;
}

function toggleRow(id: number) {
    if (isLocked.value) return;
    const next = new Set(selectedIds.value);
    if (next.has(id)) {
        next.delete(id);
    } else {
        next.add(id);
    }
    selectedIds.value = next;
}

// ── Totals ────────────────────────────────────────────────────────────────────
const selectedEmployees = computed(() => props.eligibleEmployees?.filter((e) => selectedIds.value.has(e.id)) ?? []);
const totalBonus = computed(() => selectedEmployees.value.reduce((s, e) => s + e.calculated_bonus, 0));

// ── Generate form ─────────────────────────────────────────────────────────────
const confirmForm = useForm({
    generation_id: props.existingGeneration?.id ?? null,
    bonus_id: props.bonus?.id ?? 0,
    month: props.month ?? '',
    employee_ids: [] as number[],
});

function generate() {
    confirmForm.employee_ids = Array.from(selectedIds.value);
    confirmForm.generation_id = props.existingGeneration?.id ?? null;
    confirmForm.bonus_id = props.bonus?.id ?? 0;
    confirmForm.month = props.month ?? '';
    confirmForm.post('/admin/bonuses/generate');
}
</script>

<template>
    <div class="space-y-6">
        <!-- Header -->
        <div class="flex items-center justify-between">
            <div>
                <h1 class="flex items-center gap-2 text-xl font-extrabold text-slate-800 dark:text-white">
                    <Gift class="h-6 w-6 text-indigo-600" />
                    Generate Bonus
                </h1>
                <p class="mt-0.5 text-sm text-slate-500">Select a bonus type and month, preview eligible employees, then confirm</p>
            </div>
            <a href="/admin/bonuses" class="flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700">
                <ChevronLeft class="h-4 w-4" /> Back to Bonuses
            </a>
        </div>

        <!-- Setup Card -->
        <div class="rounded-xl border border-slate-200 bg-white p-6 dark:border-slate-700 dark:bg-slate-900">
            <div class="grid grid-cols-1 gap-4 md:grid-cols-3">
                <div>
                    <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Bonus Type</label>
                    <select
                        v-model="selectedBonusId"
                        class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                    >
                        <option :value="null" disabled>Select bonus…</option>
                        <option v-for="b in bonuses" :key="b.id" :value="b.id">{{ b.name }}</option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Month</label>
                    <input
                        v-model="selectedMonth"
                        type="month"
                        class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm shadow-inner focus:ring-2 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800"
                    />
                </div>
                <div class="flex items-end">
                    <button
                        @click="loadPreview"
                        :disabled="!selectedBonusId"
                        class="w-full rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-bold text-white shadow-2xl shadow-indigo-900/30 transition-all hover:bg-indigo-700 active:scale-95 disabled:opacity-50"
                    >
                        Preview Eligible Employees
                    </button>
                </div>
            </div>
        </div>

        <!-- Preview Results -->
        <template v-if="eligibleEmployees">
            <!-- Bonus Summary Banner -->
            <div
                v-if="bonus"
                class="flex items-center gap-4 rounded-xl border border-indigo-100 bg-indigo-50 p-4 dark:border-indigo-800/30 dark:bg-indigo-900/20"
            >
                <div class="shrink-0 rounded-xl bg-indigo-600 p-3">
                    <Gift class="h-5 w-5 text-white" />
                </div>
                <div>
                    <div class="font-bold text-indigo-900 dark:text-indigo-300">{{ bonus.name }}</div>
                    <div class="text-sm text-indigo-700 dark:text-indigo-400">
                        {{
                            bonus.amount_type === 'percentage'
                                ? bonus.amount + '% of gross salary'
                                : parseFloat(bonus.amount).toLocaleString() + ' (fixed amount)'
                        }}
                        &nbsp;·&nbsp;
                        {{ new Date(month + '-01').toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) }}
                    </div>
                </div>
            </div>

            <!-- Table -->
            <div class="overflow-hidden rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
                <!-- Table Header & Search -->
                <div class="flex items-center justify-between border-b border-slate-200 px-5 py-3.5 dark:border-slate-700">
                    <div class="flex flex-1 items-center gap-6">
                        <!-- Select All checkbox -->
                        <label class="flex shrink-0 cursor-pointer items-center gap-2">
                            <input
                                type="checkbox"
                                :checked="allSelected"
                                :indeterminate="someSelected"
                                @change="toggleAll"
                                :disabled="isLocked"
                                class="h-4 w-4 cursor-pointer rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
                            />
                            <span class="text-sm font-semibold text-slate-700 dark:text-slate-300">
                                {{ allSelected ? 'Deselect All' : 'Select All' }}
                            </span>
                        </label>
                        <!-- Search input -->
                        <div class="relative w-full max-w-sm">
                            <input
                                v-model="searchQuery"
                                type="text"
                                placeholder="Search employees..."
                                class="w-full rounded-lg border border-slate-300 bg-slate-50 px-3 py-1.5 text-sm transition-colors outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-600 dark:bg-slate-800 dark:text-white dark:focus:border-indigo-400"
                            />
                            <button
                                v-if="searchQuery"
                                @click="searchQuery = ''"
                                class="absolute top-1/2 right-2.5 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                            >
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                    </div>
                    <div class="ml-4 flex shrink-0 items-center gap-2 text-sm text-slate-500">
                        <Users class="h-4 w-4" />
                        {{ filteredEmployees.length }} matched / {{ eligibleEmployees.length }} eligible
                    </div>
                </div>

                <table class="w-full">
                    <thead>
                        <tr class="border-b border-slate-100 dark:border-slate-800">
                            <th class="w-10 px-5 py-3" />
                            <th class="w-10 px-2 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">#</th>
                            <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Employee</th>
                            <th class="px-5 py-3 text-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Gross Salary</th>
                            <th class="px-5 py-3 text-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Bonus Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="(emp, i) in filteredEmployees"
                            :key="emp.id"
                            @click="toggleRow(emp.id)"
                            class="cursor-pointer border-b border-slate-50 transition-colors dark:border-slate-800"
                            :class="
                                selectedIds.has(emp.id)
                                    ? 'bg-indigo-50/60 hover:bg-indigo-50 dark:bg-indigo-900/10'
                                    : 'hover:bg-slate-50 dark:hover:bg-slate-800/30'
                            "
                        >
                            <td class="px-5 py-3.5" @click.stop>
                                <input
                                    type="checkbox"
                                    :checked="selectedIds.has(emp.id)"
                                    @change="toggleRow(emp.id)"
                                    :disabled="isLocked"
                                    class="h-4 w-4 cursor-pointer rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 disabled:cursor-not-allowed disabled:opacity-50"
                                />
                            </td>
                            <td class="px-2 py-3.5 text-xs text-slate-400">{{ i + 1 }}</td>
                            <td class="px-5 py-3.5">
                                <p class="font-semibold text-slate-800 dark:text-white">{{ emp.name }}</p>
                                <p v-if="emp.job_title" class="text-xs text-slate-500">{{ emp.job_title }}</p>
                                <p v-if="emp.department" class="text-xs text-indigo-400">{{ emp.department }}</p>
                            </td>
                            <td class="px-5 py-3.5 text-right font-mono text-sm text-slate-600 dark:text-slate-400">
                                {{ fmt(emp.gross_salary) }}
                            </td>
                            <td class="px-5 py-3.5 text-right">
                                <span
                                    class="rounded-full px-2.5 py-1 text-sm font-bold"
                                    :class="selectedIds.has(emp.id) ? 'text-emerald-700' : 'text-slate-400'"
                                >
                                    {{ fmt(emp.calculated_bonus) }}
                                </span>
                            </td>
                        </tr>
                        <tr v-if="!filteredEmployees.length">
                            <td colspan="5" class="px-5 py-12 text-center text-sm text-slate-400">
                                No eligible employees found for "{{ searchQuery }}".
                            </td>
                        </tr>
                    </tbody>
                    <!-- Total Footer -->
                    <tfoot v-if="filteredEmployees.length > 0">
                        <tr class="border-t-2 border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-800/50">
                            <td colspan="3" class="px-5 py-3.5 text-right text-sm font-bold text-slate-700 dark:text-slate-300">
                                Total ({{ selectedIds.size }} selected in total)
                            </td>
                            <td class="px-5 py-3.5 text-right font-mono text-sm font-bold text-slate-700 dark:text-slate-300">
                                {{ fmt(selectedEmployees.reduce((s, e) => s + e.gross_salary, 0)) }}
                            </td>
                            <td class="px-5 py-3.5 text-right font-mono text-base font-black text-emerald-700 dark:text-emerald-400">
                                {{ fmt(totalBonus) }}
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Confirm Generate -->
            <div v-if="eligibleEmployees.length > 0 && !isLocked" class="flex items-center justify-between">
                <p class="text-sm text-slate-500">
                    <span class="font-semibold text-slate-700 dark:text-slate-300">{{ selectedIds.size }}</span> employee{{
                        selectedIds.size !== 1 ? 's' : ''
                    }}
                    selected &nbsp;·&nbsp; Total bonus:
                    <span class="font-bold text-emerald-600">{{ fmt(totalBonus) }}</span>
                </p>
                <button
                    @click="generate"
                    :disabled="confirmForm.processing || selectedIds.size === 0"
                    class="flex items-center gap-2 rounded-xl bg-emerald-600 px-6 py-3 text-sm font-black tracking-widest text-white uppercase shadow-2xl shadow-emerald-900/30 transition-all hover:bg-emerald-700 active:scale-95 disabled:opacity-50"
                >
                    <CheckCircle class="h-4 w-4" />
                    {{ confirmForm.processing ? 'Generating…' : 'Confirm Bonus' }}
                </button>
            </div>
        </template>
    </div>
</template>
