<script setup lang="ts">
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';
import EmployeeLayout from '@/Layouts/EmployeeLayout.vue';
import Button from '@/Shared/Button.vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import { Edit2, Plus, Receipt, Send, Trash2, X } from 'lucide-vue-next';
import { computed, ref } from 'vue';

const props = defineProps<{
    loans: Array<{
        id: number;
        total_amount: string;
        installment_amount: string;
        start_month: string;
        remaining_balance: string;
        status: 'draft' | 'pending' | 'approved' | 'rejected' | 'closed';
        created_at: string;
        remarks: string | null;
        approver: { name: string } | null;
        transactions: Array<{
            id: number;
            deducted_amount: string;
            remaining_after: string;
            created_at: string;
            payroll?: {
                month_year: string;
            };
        }>;
    }>;
}>();

const formatMoney = (val: string | number) =>
    '$' + Number(val).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const statusClass = (status: string) => {
    if (status === 'draft') return 'bg-slate-100 text-slate-700';
    if (status === 'pending') return 'bg-amber-50 text-amber-600';
    if (status === 'approved' || status === 'closed') return 'bg-emerald-50 text-emerald-600';
    return 'bg-rose-50 text-rose-600';
};

const isFormModalOpen = ref(false);
const isEditing = ref(false);
const editingLoanId = ref<number | null>(null);

const form = useForm({
    total_amount: '',
    installment_amount: '',
    start_month: new Date().toISOString().substring(0, 7),
    remarks: '',
});

const resetForm = () => {
    form.reset();
    form.clearErrors();
    form.start_month = new Date().toISOString().substring(0, 7);
};

const openCreateModal = () => {
    isEditing.value = false;
    editingLoanId.value = null;
    resetForm();
    isFormModalOpen.value = true;
};

const openEditModal = (loan: (typeof props.loans)[0]) => {
    if (loan.status !== 'draft') {
        return;
    }

    isEditing.value = true;
    editingLoanId.value = loan.id;
    form.total_amount = String(loan.total_amount);
    form.installment_amount = String(loan.installment_amount);
    form.start_month = loan.start_month;
    form.remarks = loan.remarks ?? '';
    form.clearErrors();
    isFormModalOpen.value = true;
};

const saveDraft = () => {
    if (isEditing.value && editingLoanId.value) {
        form.put(`/employee/loans/${editingLoanId.value}`, {
            preserveScroll: true,
            onSuccess: () => {
                isFormModalOpen.value = false;
                resetForm();
            },
        });

        return;
    }

    form.post('/employee/loans', {
        preserveScroll: true,
        onSuccess: () => {
            isFormModalOpen.value = false;
            resetForm();
        },
    });
};

const isDeleteConfirmOpen = ref(false);
const deletingLoanId = ref<number | null>(null);
const deleteProcessing = ref(false);

const requestDeleteLoan = (loanId: number) => {
    deletingLoanId.value = loanId;
    isDeleteConfirmOpen.value = true;
};

const confirmDeleteLoan = () => {
    if (!deletingLoanId.value) {
        return;
    }

    deleteProcessing.value = true;

    router.delete(`/employee/loans/${deletingLoanId.value}`, {
        preserveScroll: true,
        onFinish: () => {
            deleteProcessing.value = false;
        },
        onSuccess: () => {
            isDeleteConfirmOpen.value = false;
            deletingLoanId.value = null;
        },
    });
};

const sendingLoanId = ref<number | null>(null);

const sendForApproval = (loanId: number) => {
    sendingLoanId.value = loanId;

    router.post(
        `/employee/loans/${loanId}/send-for-approval`,
        {},
        {
            preserveScroll: true,
            onFinish: () => {
                sendingLoanId.value = null;
            },
        },
    );
};

const selectedLoanForHistory = ref<(typeof props.loans)[0] | null>(null);
const isHistoryModalOpen = ref(false);

const openHistory = (loan: (typeof props.loans)[0]) => {
    selectedLoanForHistory.value = loan;
    isHistoryModalOpen.value = true;
};

const loanCountText = computed(() => `${props.loans.length} ${props.loans.length === 1 ? 'request' : 'requests'}`);
</script>

<template>
    <Head title="My Loans" />

    <EmployeeLayout>
        <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">My Loans</h2>
                    <p class="text-sm text-slate-500">Create draft requests, then send them for approval when ready.</p>
                    <p class="mt-1 text-xs font-semibold text-slate-400">{{ loanCountText }}</p>
                </div>

                <Button @click="openCreateModal" class="shadow-lg shadow-indigo-500/20">
                    <span class="inline-flex items-center gap-2">
                        <Plus class="h-4 w-4" />
                        Request Loan
                    </span>
                </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">Requested On</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">Deduction</th>
                            <th class="px-6 py-4 text-left font-bold tracking-wider text-slate-500 uppercase">Starts</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="transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/50">
                            <td class="px-6 py-4 font-medium text-slate-700 dark:text-slate-200">
                                {{ new Date(loan.created_at).toLocaleDateString() }}
                            </td>
                            <td class="px-6 py-4 font-bold text-slate-800 dark:text-slate-100">
                                {{ formatMoney(loan.total_amount) }}
                            </td>
                            <td class="px-6 py-4 text-slate-600 dark:text-slate-400">{{ formatMoney(loan.installment_amount) }}/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'">
                                    {{ formatMoney(loan.remaining_balance) }}
                                </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="statusClass(loan.status)">
                                    {{ loan.status }}
                                </span>
                                <div v-if="loan.status === 'rejected'" class="mt-1 text-[10px] font-medium text-slate-400">
                                    by {{ loan.approver?.name || 'Admin' }}
                                </div>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2">
                                    <div v-if="loan.status === 'draft'" class="group/tt relative">
                                        <button
                                            type="button"
                                            @click="openEditModal(loan)"
                                            title="Edit Draft"
                                            class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-slate-100 text-slate-700 transition-colors hover:bg-slate-200"
                                        >
                                            <Edit2 class="h-4 w-4" />
                                        </button>
                                        <span class="pointer-events-none absolute -top-8 left-1/2 -translate-x-1/2 rounded-md bg-slate-900 px-2 py-1 text-[10px] font-bold whitespace-nowrap text-white opacity-0 shadow-lg transition-opacity group-hover/tt:opacity-100">
                                            Edit Draft
                                        </span>
                                    </div>

                                    <div v-if="loan.status === 'draft'" class="group/tt relative">
                                        <button
                                            type="button"
                                            @click="sendForApproval(loan.id)"
                                            :disabled="sendingLoanId === loan.id"
                                            :title="sendingLoanId === loan.id ? 'Sending' : 'Send for Approval'"
                                            class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-indigo-50 text-indigo-700 transition-colors hover:bg-indigo-100 disabled:cursor-not-allowed disabled:opacity-60"
                                        >
                                            <Send class="h-4 w-4" />
                                        </button>
                                        <span class="pointer-events-none absolute -top-8 left-1/2 -translate-x-1/2 rounded-md bg-slate-900 px-2 py-1 text-[10px] font-bold whitespace-nowrap text-white opacity-0 shadow-lg transition-opacity group-hover/tt:opacity-100">
                                            {{ sendingLoanId === loan.id ? 'Sending' : 'Send for Approval' }}
                                        </span>
                                    </div>

                                    <div v-if="loan.status === 'draft'" class="group/tt relative">
                                        <button
                                            type="button"
                                            @click="requestDeleteLoan(loan.id)"
                                            title="Delete Draft"
                                            class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-rose-50 text-rose-700 transition-colors hover:bg-rose-100"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                        <span class="pointer-events-none absolute -top-8 left-1/2 -translate-x-1/2 rounded-md bg-slate-900 px-2 py-1 text-[10px] font-bold whitespace-nowrap text-white opacity-0 shadow-lg transition-opacity group-hover/tt:opacity-100">
                                            Delete Draft
                                        </span>
                                    </div>

                                    <div class="group/tt relative">
                                        <button
                                            type="button"
                                            @click="openHistory(loan)"
                                            title="View Ledger"
                                            class="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-indigo-50 text-indigo-600 transition-colors hover:bg-indigo-100"
                                        >
                                            <Receipt class="h-4 w-4" />
                                        </button>
                                        <span class="pointer-events-none absolute -top-8 left-1/2 -translate-x-1/2 rounded-md bg-slate-900 px-2 py-1 text-[10px] font-bold whitespace-nowrap text-white opacity-0 shadow-lg transition-opacity group-hover/tt:opacity-100">
                                            View Ledger
                                        </span>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="loans.length === 0">
                            <td colspan="7" class="bg-white px-6 py-12 text-center text-slate-400 italic dark:bg-slate-900">
                                You have not created any loan drafts or requests.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div v-if="isFormModalOpen" 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-900/55 transition-opacity" @click="isFormModalOpen = false"></div>

                    <div class="relative w-full max-w-xl transform overflow-hidden rounded-3xl bg-white text-left shadow-2xl transition-all dark:bg-slate-900">
                        <div class="border-b border-slate-100 px-6 py-5 dark:border-slate-800">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="text-xl font-bold text-slate-800 dark:text-white">
                                        {{ isEditing ? 'Edit Loan Draft' : 'Create Loan Draft' }}
                                    </h3>
                                    <p class="mt-1 text-xs text-slate-500">Drafts are private until you click Send for Approval.</p>
                                </div>
                                <button @click="isFormModalOpen = false" class="text-slate-400 transition-colors hover:text-slate-600">
                                    <X class="h-5 w-5" />
                                </button>
                            </div>
                        </div>

                        <form @submit.prevent="saveDraft" class="space-y-4 px-6 py-5">
                            <div class="space-y-2">
                                <label class="text-sm font-bold text-slate-700 dark:text-slate-300">Total Loan Amount</label>
                                <input
                                    type="number"
                                    v-model="form.total_amount"
                                    min="1"
                                    step="0.01"
                                    placeholder="e.g. 5000.00"
                                    class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                />
                                <p v-if="form.errors.total_amount" class="text-xs text-rose-500">{{ form.errors.total_amount }}</p>
                            </div>

                            <div class="space-y-2">
                                <label class="text-sm font-bold text-slate-700 dark:text-slate-300">Monthly Installment Deduction</label>
                                <input
                                    type="number"
                                    v-model="form.installment_amount"
                                    min="1"
                                    step="0.01"
                                    placeholder="e.g. 500.00"
                                    class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                />
                                <p class="text-[10px] font-medium text-slate-400">This amount will be deducted monthly after approval.</p>
                                <p v-if="form.errors.installment_amount" class="text-xs text-rose-500">{{ form.errors.installment_amount }}</p>
                            </div>

                            <div class="space-y-2">
                                <label class="text-sm font-bold text-slate-700 dark:text-slate-300">Start Deduction Month</label>
                                <input
                                    type="month"
                                    v-model="form.start_month"
                                    class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                />
                                <p v-if="form.errors.start_month" class="text-xs text-rose-500">{{ form.errors.start_month }}</p>
                            </div>

                            <div class="space-y-2">
                                <label class="text-sm font-bold text-slate-700 dark:text-slate-300">Reason / Remarks (Optional)</label>
                                <textarea
                                    v-model="form.remarks"
                                    placeholder="Provide context for your request if needed"
                                    rows="3"
                                    class="w-full rounded-xl border border-slate-200 bg-white p-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                                ></textarea>
                                <p v-if="form.errors.remarks" class="text-xs text-rose-500">{{ form.errors.remarks }}</p>
                            </div>
                        </form>

                        <div class="flex items-center justify-end gap-3 border-t border-slate-100 bg-slate-50 px-6 py-4 dark:border-slate-800 dark:bg-slate-900">
                            <button
                                type="button"
                                @click="isFormModalOpen = false"
                                class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
                            >
                                Cancel
                            </button>
                            <Button @click="saveDraft" class="shadow-lg shadow-indigo-500/20" :processing="form.processing">
                                {{ isEditing ? 'Update Draft' : 'Save Draft' }}
                            </Button>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="isHistoryModalOpen" 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-900/55 transition-opacity" @click="isHistoryModalOpen = false"></div>

                    <div class="relative w-full max-w-2xl transform overflow-hidden rounded-3xl bg-white text-left shadow-2xl transition-all dark:bg-slate-900">
                        <div class="space-y-6 p-6">
                            <div class="flex items-center justify-between border-b border-slate-100 pb-4 dark:border-slate-800">
                                <div>
                                    <h3 class="text-lg font-bold text-slate-800 dark:text-white">Loan Repayment Ledger</h3>
                                    <p v-if="selectedLoanForHistory" class="mt-1 text-xs text-slate-500">
                                        History of deductions for loan requested on
                                        {{ new Date(selectedLoanForHistory.created_at).toLocaleDateString() }}.
                                    </p>
                                </div>
                                <button @click="isHistoryModalOpen = false" class="text-slate-400 hover:text-slate-600">
                                    <X class="h-5 w-5" />
                                </button>
                            </div>

                            <div v-if="selectedLoanForHistory" class="space-y-6">
                                <div class="grid grid-cols-2 gap-4">
                                    <div class="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-center dark:border-white/5 dark:bg-slate-800/50">
                                        <p class="text-[10px] font-bold tracking-wider text-slate-400 uppercase">Total Loan</p>
                                        <p class="mt-1 text-xl font-black text-slate-800 dark:text-white">
                                            {{ formatMoney(selectedLoanForHistory.total_amount) }}
                                        </p>
                                    </div>
                                    <div class="rounded-2xl border border-rose-100 bg-rose-50 p-4 text-center dark:border-rose-900/20 dark:bg-rose-900/10">
                                        <p class="text-[10px] font-bold tracking-wider text-rose-400 uppercase">Remaining Balance</p>
                                        <p class="mt-1 text-xl font-black text-rose-500">{{ formatMoney(selectedLoanForHistory.remaining_balance) }}</p>
                                    </div>
                                </div>

                                <div class="overflow-hidden rounded-2xl border border-slate-100 dark:border-slate-800">
                                    <table class="w-full text-xs">
                                        <thead>
                                            <tr class="border-b border-slate-100 bg-slate-50/50 font-bold tracking-wider text-slate-500 uppercase dark:border-slate-800 dark:bg-slate-800/50">
                                                <th class="px-5 py-3 text-left">Date</th>
                                                <th class="px-5 py-3 text-left">Payroll Month</th>
                                                <th class="px-5 py-3 text-right">Deducted</th>
                                                <th class="px-5 py-3 text-right">Remaining</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                                            <tr v-for="tx in selectedLoanForHistory.transactions" :key="tx.id">
                                                <td class="px-5 py-3 text-slate-500">{{ new Date(tx.created_at).toLocaleDateString() }}</td>
                                                <td class="px-5 py-3">
                                                    <span v-if="tx.payroll" class="inline-block rounded bg-indigo-50 px-2 py-0.5 text-[9px] font-bold text-indigo-600 uppercase">
                                                        {{ tx.payroll.month_year }}
                                                    </span>
                                                    <span v-else class="text-slate-400 italic">System</span>
                                                </td>
                                                <td class="px-5 py-3 text-right font-bold text-emerald-500">-{{ formatMoney(tx.deducted_amount) }}</td>
                                                <td class="px-5 py-3 text-right font-bold text-slate-700 dark:text-slate-200">
                                                    {{ formatMoney(tx.remaining_after) }}
                                                </td>
                                            </tr>
                                            <tr v-if="selectedLoanForHistory.transactions.length === 0">
                                                <td colspan="4" class="px-5 py-10 text-center text-slate-400 italic">No deductions have occurred yet.</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end border-t border-slate-100 bg-slate-50 px-6 py-4 dark:border-slate-800 dark:bg-slate-900">
                            <Button @click="isHistoryModalOpen = false" class="w-full sm:w-auto">Close</Button>
                        </div>
                    </div>
                </div>
            </div>

            <ConfirmationModal
                :show="isDeleteConfirmOpen"
                title="Delete Draft Loan"
                message="Are you sure you want to delete this draft loan request? This action cannot be undone."
                confirm-text="Delete Draft"
                cancel-text="Cancel"
                type="danger"
                :processing="deleteProcessing"
                @close="isDeleteConfirmOpen = false"
                @confirm="confirmDeleteLoan"
            />
        </div>
    </EmployeeLayout>
</template>
