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

defineOptions({ layout: AdminLayout });

const props = defineProps<{
    increments: Array<{
        id: number;
        previous_salary: string;
        new_salary: string;
        increment_percentage: string;
        effective_date: string;
        reason: string | null;
        status: 'pending' | 'approved' | 'rejected';
        employee: { id: number; name: string };
        approved_by: { name: string } | null;
    }>;
    employees: Array<{
        id: number;
        name: string;
        salary_assignment: { gross_salary: string } | null;
    }>;
}>();

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

const form = useForm({
    employee_id: 0,
    new_salary: '',
    effective_date: new Date().toISOString().split('T')[0],
    reason: '',
});

const selectedEmployee = ref<(typeof props.employees)[0] | null>(null);

function onEmployeeChange() {
    selectedEmployee.value = props.employees.find((e) => e.id === form.employee_id) ?? null;
}

function openCreate() {
    editing.value = null;
    form.reset();
    form.effective_date = new Date().toISOString().split('T')[0];
    selectedEmployee.value = null;
    showForm.value = true;
}

function openEdit(inc: (typeof props.increments)[0]) {
    editing.value = inc.id;
    form.employee_id = inc.employee.id;
    form.new_salary = inc.new_salary;
    form.effective_date = inc.effective_date;
    form.reason = inc.reason ?? '';
    selectedEmployee.value = props.employees.find((e) => e.id === inc.employee.id) ?? null;
    showForm.value = true;
}

function submit() {
    if (editing.value) {
        form.put(update({ salaryIncrement: editing.value }).url, {
            preserveScroll: true,
            onSuccess: () => {
                showForm.value = false;
                form.reset();
            },
        });
    } else {
        form.post(store().url, {
            preserveScroll: true,
            onSuccess: () => {
                showForm.value = false;
                form.reset();
            },
        });
    }
}

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

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

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

const statusClass: Record<string, string> = {
    pending: 'bg-amber-50 text-amber-700',
    approved: 'bg-emerald-50 text-emerald-700',
    rejected: 'bg-red-50 text-red-700',
};
</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">Salary Increments</h1>
                <p class="text-sm text-slate-500">Submit salary increment requests — approved increments are applied automatically</p>
            </div>
            <div class="flex gap-3">
                <Link
                    href="/admin/payroll/approvals"
                    class="flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-bold text-slate-700 transition-all hover:bg-slate-50"
                >
                    <BadgeCheck class="h-4 w-4 text-indigo-600" /> Approvals
                </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 Increment
                </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 Increment Request' : 'New Salary Increment' }}
                        </h2>
                        <button @click="showForm = false"><X class="h-5 w-5 text-slate-400" /></button>
                    </div>
                    <div class="flex-1 space-y-4 overflow-y-auto p-5">
                        <div
                            class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700 dark:border-amber-800/30 dark:bg-amber-900/20"
                        >
                            This increment will be submitted as <strong>pending</strong>. The salary will only be updated after approval.
                        </div>

                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Employee</label>
                            <SearchableSelect
                                v-model="form.employee_id"
                                :options="employees"
                                placeholder="Select employee..."
                                :disabled="!!editing"
                                @update:model-value="onEmployeeChange"
                            />
                            <p v-if="form.errors.employee_id" class="mt-1 text-xs text-red-500">{{ form.errors.employee_id }}</p>
                        </div>

                        <div
                            v-if="selectedEmployee?.salary_assignment"
                            class="rounded-xl bg-slate-50 p-3 text-sm text-slate-600 dark:bg-slate-800 dark:text-slate-400"
                        >
                            Current Gross Salary:
                            <span class="font-bold text-slate-800 dark:text-white">
                                {{ parseFloat(selectedEmployee.salary_assignment.gross_salary).toLocaleString() }}
                            </span>
                        </div>

                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">New Gross Salary</label>
                            <input
                                v-model="form.new_salary"
                                type="number"
                                min="1"
                                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.new_salary" class="mt-1 text-xs text-red-500">{{ form.errors.new_salary }}</p>
                        </div>

                        <div>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Effective Date (on approval)</label>
                            <input
                                v-model="form.effective_date"
                                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>
                            <label class="mb-1 block text-sm font-medium text-slate-700 dark:text-slate-300">Reason</label>
                            <textarea
                                v-model="form.reason"
                                rows="3"
                                placeholder="Annual review, performance award, etc."
                                class="w-full rounded-xl border border-slate-300 bg-white p-3 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…' : editing ? 'Update' : 'Submit for Approval' }}
                        </button>
                    </div>
                </div>
            </Transition>
        </Teleport>

        <!-- History 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-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Previous</th>
                        <th class="px-5 py-3 text-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">New Salary</th>
                        <th class="px-5 py-3 text-right text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Increment</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Effective Date</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Status</th>
                        <th class="px-5 py-3 text-left text-[10px] font-semibold tracking-widest text-slate-400 uppercase">Reason</th>
                        <th class="px-5 py-3" />
                    </tr>
                </thead>
                <tbody>
                    <tr
                        v-for="inc in increments"
                        :key="inc.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">{{ inc.employee.name }}</td>
                        <td class="px-5 py-3 text-right font-mono text-sm text-slate-400">
                            {{ parseFloat(inc.previous_salary).toLocaleString() }}
                        </td>
                        <td class="px-5 py-3 text-right font-mono text-sm font-semibold text-slate-700 dark:text-slate-300">
                            {{ parseFloat(inc.new_salary).toLocaleString() }}
                        </td>
                        <td class="px-5 py-3 text-right">
                            <span
                                class="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700"
                            >
                                <TrendingUp class="h-3 w-3" />
                                +{{ parseFloat(inc.increment_percentage).toFixed(2) }}%
                            </span>
                        </td>
                        <td class="px-5 py-3 text-sm text-slate-500">{{ inc.effective_date }}</td>
                        <td class="px-5 py-3">
                            <span :class="statusClass[inc.status]" class="rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize">
                                {{ inc.status }}
                            </span>
                        </td>
                        <td class="max-w-xs truncate px-5 py-3 text-sm text-slate-500">{{ inc.reason ?? '-' }}</td>
                        <td class="px-5 py-3">
                            <div v-if="inc.status === 'pending'" class="flex items-center justify-end gap-1">
                                <button
                                    @click="openEdit(inc)"
                                    class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-700"
                                    title="Edit"
                                >
                                    <Pencil class="h-4 w-4 text-slate-500" />
                                </button>
                                <button
                                    @click="deleteIncrement(inc.id)"
                                    class="rounded-lg p-1.5 transition-colors hover:bg-red-50 dark:hover:bg-red-900/20"
                                    title="Delete"
                                >
                                    <Trash2 class="h-4 w-4 text-red-500" />
                                </button>
                            </div>
                            <div v-else class="flex justify-end">
                                <span class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-400">
                                    {{ inc.approved_by?.name ?? '—' }}
                                </span>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="!increments.length">
                        <td colspan="8" class="px-5 py-10 text-center text-sm text-slate-400">No increment records yet.</td>
                    </tr>
                </tbody>
            </table>
        </div>

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