<script setup lang="ts">
import { preview, store } from '@/actions/App/Http/Controllers/Admin/EmployeeSalaryAssignmentController';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { useForm } from '@inertiajs/vue3';
import axios from 'axios';
import { ref, watch } from 'vue';

defineOptions({ layout: AdminLayout });

defineProps<{
    employees: Array<{
        id: number;
        name: string;
        employee_profile: { job_title: string | null; department_rel: { name: string } | null } | null;
        salary_assignment: {
            gross_salary: string;
            salary_type: string;
            payroll_structure: { id: number; name: string };
        } | null;
    }>;
    structures: Array<{
        id: number;
        name: string;
        components: Array<{
            salary_component: { name: string; type: string };
            calculation_type: string;
            value: string;
        }>;
    }>;
}>();

const showForm = ref(false);
const selectedEmployee = ref<any>(null);
const breakdown = ref<any>(null);
const loadingPreview = ref(false);

const form = useForm({
    employee_id: 0,
    payroll_structure_id: 0,
    salary_type: 'monthly' as 'monthly' | 'yearly',
    gross_salary: '',
    effective_from: '',
});

function openAssign(emp: any) {
    selectedEmployee.value = emp;
    const sa = emp.salary_assignment;
    form.employee_id = emp.id;
    form.payroll_structure_id = sa?.payroll_structure?.id ?? 0;
    form.salary_type = sa?.salary_type ?? 'monthly';
    form.gross_salary = sa?.gross_salary ?? '';
    form.effective_from = new Date().toISOString().split('T')[0];
    breakdown.value = null;
    showForm.value = true;
}

async function loadPreview() {
    if (!form.payroll_structure_id || !form.gross_salary) return;
    loadingPreview.value = true;
    try {
        const { data } = await axios.post(preview().url, {
            employee_id: form.employee_id,
            payroll_structure_id: form.payroll_structure_id,
            gross_salary: form.gross_salary,
        });
        breakdown.value = data;
    } finally {
        loadingPreview.value = false;
    }
}

watch(() => [form.payroll_structure_id, form.gross_salary], loadPreview);

function submit() {
    form.post(store().url, {
        preserveScroll: true,
        onSuccess: () => {
            showForm.value = false;
        },
    });
}
</script>

<template>
    <div class="space-y-6">
        <div>
            <h1 class="text-xl font-extrabold text-slate-800 dark:text-white">Salary Assignments</h1>
            <p class="text-sm text-slate-500">Assign payroll structures and gross salaries to employees</p>
        </div>

        <!-- Slide-over Form -->
        <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-lg flex-col bg-white shadow-2xl dark:bg-slate-900"
                >
                    <div class="border-b border-slate-200 p-5 dark:border-slate-700">
                        <h2 class="text-base font-bold text-slate-800 dark:text-white">Assign Salary — {{ selectedEmployee?.name }}</h2>
                    </div>
                    <div class="flex-1 space-y-4 overflow-y-auto p-5">
                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Payroll Structure</label>
                            <select
                                v-model="form.payroll_structure_id"
                                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="0" disabled>Select structure</option>
                                <option v-for="s in structures" :key="s.id" :value="s.id">{{ s.name }}</option>
                            </select>
                        </div>
                        <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">Salary Type</label>
                                <select
                                    v-model="form.salary_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="monthly">Monthly</option>
                                    <option value="yearly">Yearly</option>
                                </select>
                            </div>
                            <div>
                                <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Effective From</label>
                                <input
                                    v-model="form.effective_from"
                                    type="date"
                                    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>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Gross Salary</label>
                            <input
                                v-model="form.gross_salary"
                                type="number"
                                min="1"
                                step="0.01"
                                placeholder="Enter gross salary"
                                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>

                        <!-- Live Breakdown Preview -->
                        <div v-if="loadingPreview" class="animate-pulse py-4 text-center text-sm text-slate-400">Calculating…</div>
                        <div v-else-if="breakdown" class="space-y-3 rounded-xl bg-slate-50 p-4 dark:bg-slate-800">
                            <div>
                                <p class="mb-2 text-xs font-semibold tracking-widest text-slate-500 uppercase">Earnings</p>
                                <div
                                    v-for="e in breakdown.salary_breakdown.earnings"
                                    :key="e.name"
                                    class="flex justify-between border-b border-slate-200 py-1 text-sm text-slate-700 dark:border-slate-700 dark:text-slate-300"
                                >
                                    <span>{{ e.name }} {{ e.type === 'percentage' ? '(' + e.value + '%)' : '' }}</span>
                                    <span class="font-semibold">{{ e.amount.toLocaleString() }}</span>
                                </div>
                            </div>
                            <div>
                                <p class="mb-2 text-xs font-semibold tracking-widest text-slate-500 uppercase">Deductions</p>
                                <div
                                    v-for="d in breakdown.salary_breakdown.deductions"
                                    :key="d.name"
                                    class="flex justify-between border-b border-slate-200 py-1 text-sm text-slate-700 dark:border-slate-700 dark:text-slate-300"
                                >
                                    <span>{{ d.name }}</span>
                                    <span class="font-semibold text-rose-600">-{{ d.amount.toLocaleString() }}</span>
                                </div>
                            </div>
                            <div class="flex justify-between pt-2 text-sm font-black text-indigo-600 dark:text-indigo-400">
                                <span>Net Salary</span>
                                <span>{{ breakdown.net_salary.toLocaleString() }}</span>
                            </div>
                        </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…' : 'Assign Salary' }}
                        </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">Employee</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Department</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Structure</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" />
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="emp in employees"
                        :key="emp.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">{{ emp.name }}</td>
                        <td class="px-5 py-3 text-sm text-slate-500">{{ emp.employee_profile?.department_rel?.name ?? '-' }}</td>
                        <td class="px-5 py-3">
                            <span v-if="emp.salary_assignment" class="rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-semibold text-indigo-700">
                                {{ emp.salary_assignment.payroll_structure?.name ?? '-' }}
                            </span>
                            <span v-else class="text-xs text-slate-400 italic">Not assigned</span>
                        </td>
                        <td class="px-5 py-3 text-right font-mono font-semibold text-slate-700 dark:text-slate-300">
                            {{ emp.salary_assignment ? parseFloat(emp.salary_assignment.gross_salary).toLocaleString() : '-' }}
                        </td>
                        <td class="px-5 py-3 text-right">
                            <button
                                @click="openAssign(emp)"
                                class="rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-bold text-white transition-all hover:bg-indigo-700 active:scale-95"
                            >
                                {{ emp.salary_assignment ? 'Edit' : 'Assign' }}
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>
