<script setup lang="ts">
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { Edit2, Eye, Plus, X } from 'lucide-vue-next';
import { ref } from 'vue';

const props = defineProps<{
    loans: Array<{
        id: number;
        loan_date: string | null;
        total_amount: string;
        installment_amount: string;
        start_month: string;
        remaining_balance: string;
        status: 'pending' | 'approved' | 'rejected' | 'closed';
        created_at: string;
        employee: {
            id: number;
            name: string;
            email: string;
        };
    }>;
    employees: Array<{
        id: number;
        name: string;
    }>;
}>();

const showModal = ref(false);
const isEditing = ref(false);
const editingId = ref<number | null>(null);

const form = useForm({
    employee_id: '',
    loan_date: new Date().toISOString().substring(0, 7), // YYYY-MM
    total_amount: '',
    installment_amount: '',
    start_month: new Date().toISOString().substring(0, 7), // YYYY-MM
    remarks: '',
});

const openCreateModal = () => {
    isEditing.value = false;
    editingId.value = null;
    form.reset();
    showModal.value = true;
};

const openEditModal = (loan: any) => {
    isEditing.value = true;
    editingId.value = loan.id;
    form.employee_id = loan.employee.id.toString();
    form.loan_date = loan.loan_date || new Date().toISOString().substring(0, 7);
    form.total_amount = loan.total_amount;
    form.installment_amount = loan.installment_amount;
    form.start_month = loan.start_month;
    form.remarks = loan.remarks || '';
    showModal.value = true;
};

const submitLoan = () => {
    if (isEditing.value && editingId.value) {
        form.put(`/admin/loans/${editingId.value}`, {
            onSuccess: () => {
                showModal.value = false;
                form.reset();
            },
        });
    } else {
        form.post('/admin/loans', {
            onSuccess: () => {
                showModal.value = false;
                form.reset();
            },
        });
    }
};
</script>

<template>
    <Head title="Loan Requests" />

    <AdminLayout>
        <div class="space-y-6">
            <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
                <div>
                    <h2 class="text-2xl font-semibold tracking-tight text-slate-800 dark:text-white">Employee Loans</h2>
                    <p class="text-sm text-slate-500">Manage employee loan requests, approvals, and balances.</p>
                </div>
                <button
                    @click="openCreateModal"
                    class="flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-bold text-white shadow-sm transition-all hover:bg-indigo-700 active:scale-95"
                >
                    <Plus class="h-4 w-4 text-white" />
                    New Loan Request
                </button>
            </div>

            <div class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-slate-100 bg-slate-50/50 dark:border-slate-800 dark:bg-slate-800/50">
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Employee</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Amount</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Installment</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Start Month</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Remaining</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Status</th>
                            <th class="px-6 py-4 text-right font-bold tracking-wider text-slate-500 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                        <tr v-for="loan in loans" :key="loan.id" class="group transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/50">
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-3">
                                    <div
                                        class="flex h-9 w-9 items-center justify-center rounded-full bg-indigo-100 text-xs font-bold text-indigo-700 dark:bg-indigo-900/50 dark:text-indigo-300"
                                    >
                                        {{ loan.employee.name.substring(0, 2).toUpperCase() }}
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-slate-700 dark:text-slate-200">{{ loan.employee.name }}</p>
                                        <p class="text-xs text-slate-400">{{ loan.employee.email }}</p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 font-bold text-slate-700 dark:text-slate-200">
                                {{ Number(loan.total_amount).toLocaleString() }}
                            </td>
                            <td class="px-6 py-4 text-slate-600 dark:text-slate-400">{{ Number(loan.installment_amount).toLocaleString() }}/mo</td>
                            <td class="px-6 py-4 text-slate-600 capitalize dark:text-slate-400">
                                {{ loan.start_month }}
                            </td>
                            <td class="px-6 py-4">
                                <span :class="Number(loan.remaining_balance) > 0 ? 'font-bold text-rose-500' : 'font-bold text-emerald-500'">
                                    {{ Number(loan.remaining_balance).toLocaleString() }}
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <span
                                    class="inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-bold tracking-wider uppercase"
                                    :class="{
                                        'bg-emerald-50 text-emerald-600': loan.status === 'approved' || loan.status === 'closed',
                                        'bg-rose-50 text-rose-600': loan.status === 'rejected',
                                        'bg-amber-50 text-amber-600': loan.status === 'pending',
                                        'bg-slate-50 text-slate-500': loan.status === 'closed',
                                    }"
                                >
                                    {{ loan.status }}
                                </span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                                    <button
                                        v-if="loan.status === 'pending'"
                                        type="button"
                                        class="flex h-8 w-8 items-center justify-center rounded-lg text-amber-500 transition-colors hover:bg-amber-50"
                                        @click="openEditModal(loan)"
                                        title="Edit"
                                    >
                                        <Edit2 class="h-4 w-4" />
                                    </button>
                                    <Link
                                        :href="`/admin/loans/${loan.id}`"
                                        class="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-slate-100"
                                        title="View Details"
                                    >
                                        <Eye class="h-4 w-4" />
                                    </Link>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="loans.length === 0">
                            <td colspan="7" class="bg-white px-6 py-12 text-center font-medium text-slate-400 italic dark:bg-slate-900">
                                No loan requests found.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Loan Modal (Create/Edit) -->
        <div v-if="showModal" class="fixed inset-0 z-50 overflow-y-auto">
            <div class="flex min-h-screen items-center justify-center p-4 text-center">
                <div class="fixed inset-0 bg-slate-500/50 backdrop-blur-sm transition-opacity" @click="showModal = false"></div>

                <div
                    class="relative w-full max-w-md transform overflow-hidden rounded-3xl bg-white text-left shadow-2xl transition-all dark:bg-slate-900"
                >
                    <div class="p-6">
                        <div class="flex items-center justify-between">
                            <h3 class="text-xl font-bold text-slate-800 dark:text-white">
                                {{ isEditing ? 'Edit Loan Request' : 'Create Loan Request' }}
                            </h3>
                            <button @click="showModal = false" class="text-slate-400 transition-colors hover:text-slate-600">
                                <X class="h-5 w-5" />
                            </button>
                        </div>

                        <form @submit.prevent="submitLoan" class="mt-6 space-y-4">
                            <div>
                                <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Employee</label>
                                <select
                                    v-model="form.employee_id"
                                    required
                                    class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                >
                                    <option value="" disabled>Select Employee</option>
                                    <option v-for="emp in employees" :key="emp.id" :value="emp.id">
                                        {{ emp.name }}
                                    </option>
                                </select>
                                <p v-if="form.errors.employee_id" class="mt-1 text-xs text-rose-500">{{ form.errors.employee_id }}</p>
                            </div>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Total Amount</label>
                                    <input
                                        v-model="form.total_amount"
                                        type="number"
                                        step="0.01"
                                        required
                                        placeholder="0.00"
                                        class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                    />
                                    <p v-if="form.errors.total_amount" class="mt-1 text-xs text-rose-500">{{ form.errors.total_amount }}</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Monthly Installment</label>
                                    <input
                                        v-model="form.installment_amount"
                                        type="number"
                                        step="0.01"
                                        required
                                        placeholder="0.00"
                                        class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                    />
                                    <p v-if="form.errors.installment_amount" class="mt-1 text-xs text-rose-500">
                                        {{ form.errors.installment_amount }}
                                    </p>
                                </div>
                            </div>

                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Loan Issue Month</label>
                                    <input
                                        v-model="form.loan_date"
                                        type="month"
                                        required
                                        class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                    />
                                    <p class="mt-1 text-[10px] text-slate-400">Month when the loan was issued</p>
                                    <p v-if="form.errors.loan_date" class="mt-1 text-xs text-rose-500">{{ form.errors.loan_date }}</p>
                                </div>
                                <div>
                                    <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Installment Start Month</label>
                                    <input
                                        v-model="form.start_month"
                                        type="month"
                                        required
                                        class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                    />
                                    <p class="mt-1 text-[10px] text-slate-400">First month deduction applies</p>
                                    <p v-if="form.errors.start_month" class="mt-1 text-xs text-rose-500">{{ form.errors.start_month }}</p>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-bold text-slate-700 dark:text-slate-300">Remarks</label>
                                <textarea
                                    v-model="form.remarks"
                                    rows="3"
                                    placeholder="Enter additional details..."
                                    class="mt-1 block w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-2 text-sm focus:border-indigo-500 focus:ring-indigo-500 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                ></textarea>
                                <p v-if="form.errors.remarks" class="mt-1 text-xs text-rose-500">{{ form.errors.remarks }}</p>
                            </div>

                            <div class="mt-6 flex justify-end gap-3">
                                <button
                                    type="button"
                                    @click="showModal = false"
                                    class="px-5 py-2.5 text-sm font-bold text-slate-500 transition-colors hover:text-slate-700"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    :disabled="form.processing"
                                    class="rounded-xl bg-indigo-600 px-6 py-2.5 text-sm font-bold text-white shadow-lg shadow-indigo-100 transition-all hover:bg-indigo-700 active:scale-95 disabled:opacity-50 dark:shadow-none"
                                >
                                    {{ form.processing ? (isEditing ? 'Updating...' : 'Creating...') : isEditing ? 'Update Loan' : 'Create Loan' }}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
