<script setup lang="ts">
import { generate } from '@/actions/App/Http/Controllers/Admin/PayrollController';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { useForm } from '@inertiajs/vue3';
import { CheckSquare, Pencil, Square } from 'lucide-vue-next';
import { computed, reactive, ref } from 'vue';

defineOptions({ layout: AdminLayout });

const props = defineProps<{
    preview: {
        month: string;
        total: number;
        employees: Array<{
            employee_id: number;
            name: string;
            job_title: string | null;
            department: string | null;
            gross_salary: number;
            total_earnings: number;
            total_deductions: number;
            tax_deduction: number;
            loan_deduction: number;
            net_salary: number;
        }>;
    };
    existingPayroll: { id: number; status: string } | null;
    month: string;
}>();

const selectedIds = ref<number[]>(props.preview.employees.map((e) => e.employee_id));

const isApproved = props.existingPayroll?.status === 'approved';

function toggleAll() {
    if (selectedIds.value.length === props.preview.employees.length) {
        selectedIds.value = [];
    } else {
        selectedIds.value = props.preview.employees.map((e) => e.employee_id);
    }
}

function toggle(id: number) {
    if (selectedIds.value.includes(id)) {
        selectedIds.value = selectedIds.value.filter((x) => x !== id);
    } else {
        selectedIds.value.push(id);
    }
}

// ─── Per-employee adjustments ─────────────────────────────────────────────────
type Adjustment = {
    addition: number;
    deduction: number;
    editingAddition: boolean;
    editingDeduction: boolean;
    additionInput: string;
    deductionInput: string;
};

const adjustments = reactive<Record<number, Adjustment>>({});

function getAdj(empId: number): Adjustment {
    if (!adjustments[empId]) {
        adjustments[empId] = { addition: 0, deduction: 0, editingAddition: false, editingDeduction: false, additionInput: '0', deductionInput: '0' };
    }
    return adjustments[empId];
}

function startEditAddition(empId: number) {
    const adj = getAdj(empId);
    adj.additionInput = String(adj.addition || '');
    adj.editingAddition = true;
}

function commitAddition(empId: number) {
    const adj = getAdj(empId);
    const val = parseFloat(adj.additionInput);
    adj.addition = isNaN(val) || val < 0 ? 0 : val;
    adj.editingAddition = false;
}

function startEditDeduction(empId: number) {
    const adj = getAdj(empId);
    adj.deductionInput = String(adj.deduction || '');
    adj.editingDeduction = true;
}

function commitDeduction(empId: number) {
    const adj = getAdj(empId);
    const val = parseFloat(adj.deductionInput);
    adj.deduction = isNaN(val) || val < 0 ? 0 : val;
    adj.editingDeduction = false;
}

function computedNet(emp: (typeof props.preview.employees)[0]): number {
    const adj = adjustments[emp.employee_id];
    const add = adj?.addition ?? 0;
    const ded = adj?.deduction ?? 0;
    return Math.round((emp.net_salary + add - ded) * 100) / 100;
}

// ─── Form submission ──────────────────────────────────────────────────────────
const form = useForm({ month: props.month, employee_ids: [] as number[], adjustments: [] as any[] });

function confirm() {
    form.employee_ids = selectedIds.value;
    form.adjustments = Object.entries(adjustments)
        .filter(([empId]) => selectedIds.value.includes(Number(empId)))
        .map(([empId, adj]) => ({
            employee_id: Number(empId),
            addition: adj.addition,
            deduction: adj.deduction,
        }));
    form.post(generate().url);
}

const totalNet = computed(() =>
    props.preview.employees.filter((e) => selectedIds.value.includes(e.employee_id)).reduce((sum, e) => sum + computedNet(e), 0),
);

function fmt(val: number): string {
    return val.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
</script>

<script lang="ts"></script>

<template>
    <div class="space-y-6">
        <div>
            <h1 class="text-xl font-extrabold text-slate-800 dark:text-white">
                Generate Payroll — {{ new Date(preview.month).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) }}
            </h1>
            <p v-if="isApproved" class="mt-1 text-sm font-semibold text-red-500">⚠ This payroll is approved and locked. It cannot be regenerated.</p>
            <p v-else-if="existingPayroll" class="mt-1 text-sm font-semibold text-amber-500">⚠ Existing pending payroll will be overwritten.</p>
            <p v-else class="mt-1 text-sm text-slate-500">
                Review and confirm the employee selection below. Use Addition/Deduction to enter one-time adjustments.
            </p>
        </div>

        <div class="overflow-x-auto rounded-xl border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-slate-200 dark:border-slate-700">
                        <th class="px-3 py-3">
                            <button @click="toggleAll" :disabled="isApproved" class="flex items-center text-indigo-600">
                                <component :is="selectedIds.length === preview.employees.length ? CheckSquare : Square" class="h-4 w-4" />
                            </button>
                        </th>
                        <th class="px-3 py-3 text-left text-[10px] font-bold tracking-widest text-slate-400 uppercase">Employee</th>
                        <th class="px-3 py-3 text-right text-[10px] font-bold tracking-widest text-slate-400 uppercase">Gross</th>
                        <th class="px-3 py-3 text-right text-[10px] font-bold tracking-widest text-slate-400 uppercase">Earnings</th>
                        <th class="px-3 py-3 text-right text-[10px] font-bold tracking-widest text-amber-500 uppercase">Income Tax</th>
                        <th class="px-3 py-3 text-right text-[10px] font-bold tracking-widest text-rose-400 uppercase">Loan</th>
                        <th class="px-3 py-3 text-center text-[10px] font-bold tracking-widest text-emerald-500 uppercase">Addition</th>
                        <th class="px-3 py-3 text-center text-[10px] font-bold tracking-widest text-rose-500 uppercase">Deduction</th>
                        <th class="px-3 py-3 text-right text-[10px] font-bold tracking-widest text-indigo-500 uppercase">Net</th>
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="emp in preview.employees"
                        :key="emp.employee_id"
                        :class="{ 'opacity-40': !selectedIds.includes(emp.employee_id) }"
                        class="border-b border-slate-100 transition-colors hover:bg-slate-50 dark:border-slate-800 dark:hover:bg-slate-800/40"
                    >
                        <!-- Checkbox -->
                        <td class="px-3 py-3">
                            <button @click="toggle(emp.employee_id)" :disabled="isApproved" class="flex items-center text-indigo-600">
                                <component :is="selectedIds.includes(emp.employee_id) ? CheckSquare : Square" class="h-4 w-4" />
                            </button>
                        </td>

                        <!-- Employee info stacked -->
                        <td class="px-3 py-3">
                            <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>

                        <!-- Gross -->
                        <td class="px-3 py-3 text-right font-mono text-slate-700 dark:text-slate-300">{{ fmt(emp.gross_salary) }}</td>

                        <!-- Earnings -->
                        <td class="px-3 py-3 text-right font-mono text-emerald-600">{{ fmt(emp.total_earnings) }}</td>

                        <!-- Income Tax (negative sign) -->
                        <td class="px-3 py-3 text-right font-mono text-amber-600">
                            <span v-if="emp.tax_deduction > 0">−{{ fmt(emp.tax_deduction) }}</span>
                            <span v-else class="text-slate-300">—</span>
                        </td>

                        <!-- Loan (negative sign) -->
                        <td class="px-3 py-3 text-right font-mono text-rose-500">
                            <span v-if="emp.loan_deduction > 0">−{{ fmt(emp.loan_deduction) }}</span>
                            <span v-else class="text-slate-300">—</span>
                        </td>

                        <!-- Addition column -->
                        <td class="px-3 py-2 text-center">
                            <div v-if="getAdj(emp.employee_id).editingAddition" class="flex items-center justify-center gap-1">
                                <input
                                    v-model="getAdj(emp.employee_id).additionInput"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-24 rounded-lg border border-emerald-300 bg-emerald-50 px-2 py-1 text-right font-mono text-xs focus:ring-2 focus:ring-emerald-400 focus:outline-none dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                                    @blur="commitAddition(emp.employee_id)"
                                    @keyup.enter="commitAddition(emp.employee_id)"
                                    @keyup.escape="getAdj(emp.employee_id).editingAddition = false"
                                    autofocus
                                />
                            </div>
                            <button
                                v-else
                                @click="startEditAddition(emp.employee_id)"
                                :disabled="isApproved"
                                class="group inline-flex items-center gap-1 rounded-lg px-2 py-1 font-mono text-xs transition-colors hover:bg-emerald-50 dark:hover:bg-emerald-900/20"
                                :class="getAdj(emp.employee_id).addition > 0 ? 'font-semibold text-emerald-600' : 'text-slate-400'"
                            >
                                <span>+{{ fmt(getAdj(emp.employee_id).addition) }}</span>
                                <Pencil class="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-100" />
                            </button>
                        </td>

                        <!-- Deduction column -->
                        <td class="px-3 py-2 text-center">
                            <div v-if="getAdj(emp.employee_id).editingDeduction" class="flex items-center justify-center gap-1">
                                <input
                                    v-model="getAdj(emp.employee_id).deductionInput"
                                    type="number"
                                    min="0"
                                    step="0.01"
                                    class="w-24 rounded-lg border border-rose-300 bg-rose-50 px-2 py-1 text-right font-mono text-xs focus:ring-2 focus:ring-rose-400 focus:outline-none dark:border-slate-600 dark:bg-slate-800 dark:text-white"
                                    @blur="commitDeduction(emp.employee_id)"
                                    @keyup.enter="commitDeduction(emp.employee_id)"
                                    @keyup.escape="getAdj(emp.employee_id).editingDeduction = false"
                                    autofocus
                                />
                            </div>
                            <button
                                v-else
                                @click="startEditDeduction(emp.employee_id)"
                                :disabled="isApproved"
                                class="group inline-flex items-center gap-1 rounded-lg px-2 py-1 font-mono text-xs transition-colors hover:bg-rose-50 dark:hover:bg-rose-900/20"
                                :class="getAdj(emp.employee_id).deduction > 0 ? 'font-semibold text-rose-600' : 'text-slate-400'"
                            >
                                <span>−{{ fmt(getAdj(emp.employee_id).deduction) }}</span>
                                <Pencil class="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-100" />
                            </button>
                        </td>

                        <!-- Adjusted Net -->
                        <td class="px-3 py-3 text-right font-mono font-bold text-indigo-600">
                            {{ fmt(computedNet(emp)) }}
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr class="border-t-2 border-slate-200 bg-slate-50 dark:border-slate-700 dark:bg-slate-800">
                        <td colspan="8" class="px-3 py-3 text-sm font-bold text-slate-600 dark:text-slate-400">
                            Selected: {{ selectedIds.length }} of {{ preview.employees.length }} employees
                        </td>
                        <td class="px-3 py-3 text-right font-mono text-base font-black text-indigo-700 dark:text-indigo-400">
                            {{ fmt(totalNet) }}
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <div class="flex justify-end">
            <button
                v-if="!isApproved"
                @click="confirm"
                :disabled="form.processing || selectedIds.length === 0"
                class="rounded-xl bg-indigo-600 px-6 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…' : 'Confirm & Generate Payroll' }}
            </button>
        </div>
    </div>
</template>
