<script setup lang="ts">
import AdminLayout from '@/Layouts/AdminLayout.vue';
import Button from '@/Shared/Button.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { ArrowLeft, Banknote, Wallet } from 'lucide-vue-next';

const props = defineProps<{
    loan: {
        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;
        remarks: string | null;
        employee: {
            id: number;
            name: string;
            email: string;
        };
        approver: {
            name: string;
        } | null;
        approved_at: string | null;
        transactions: Array<{
            id: number;
            source: 'payroll' | 'manual' | string;
            note: string | null;
            deducted_amount: string;
            remaining_after: string;
            created_at: string;
            payroll?: {
                id: number;
                month_year: string;
            };
            recorder?: {
                name: string;
            } | null;
        }>;
    };
}>();

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

const manualRepaymentForm = useForm({
    amount: '',
    note: '',
});

const submitManualRepayment = () => {
    manualRepaymentForm.post(`/admin/loans/${props.loan.id}/manual-repayment`, {
        preserveScroll: true,
        onSuccess: () => {
            manualRepaymentForm.reset();
        },
    });
};
</script>

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

    <AdminLayout>
        <div class="space-y-6">
            <div class="flex items-center gap-4">
                <Link
                    href="/admin/loans"
                    class="flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 shadow-sm transition-colors hover:bg-slate-50"
                >
                    <ArrowLeft class="h-5 w-5" />
                </Link>
                <div>
                    <h2 class="text-2xl font-semibold tracking-tight text-slate-800 dark:text-white">Loan Verification & Ledger</h2>
                    <p class="text-sm text-slate-500">View details for loan request #{{ loan.id }}</p>
                </div>
            </div>

            <div class="grid gap-6 lg:grid-cols-3">
                <!-- Overview Card -->
                <div
                    class="flex flex-col gap-6 rounded-[2rem] border border-slate-200 bg-white p-6 shadow-sm lg:col-span-1 dark:border-slate-800 dark:bg-slate-900"
                >
                    <div>
                        <h3 class="text-lg font-bold text-slate-800 dark:text-white">Overview</h3>
                        <p class="mt-1 text-sm text-slate-500">Primary terms of the agreed loan.</p>
                    </div>

                    <div class="flex items-center gap-4">
                        <div
                            class="flex h-14 w-14 items-center justify-center rounded-2xl bg-indigo-50 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400"
                        >
                            <Wallet class="h-7 w-7" />
                        </div>
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Total Amount</p>
                            <p class="text-3xl font-black text-slate-800 dark:text-white">{{ formatMoney(loan.total_amount) }}</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-x-4 gap-y-6 border-t border-slate-100 pt-6 dark:border-slate-800">
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Monthly Installment</p>
                            <p class="mt-1.5 font-bold text-slate-700 dark:text-slate-200">{{ formatMoney(loan.installment_amount) }}</p>
                        </div>
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Loan Issue Month</p>
                            <p class="mt-1.5 font-bold text-slate-700 dark:text-slate-200">{{ loan.loan_date ?? '—' }}</p>
                        </div>
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Installment Start Month</p>
                            <p class="mt-1.5 font-bold text-slate-700 capitalize dark:text-slate-200">{{ loan.start_month }}</p>
                        </div>
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Remaining Balance</p>
                            <p class="mt-1.5 font-bold text-rose-500">{{ formatMoney(loan.remaining_balance) }}</p>
                        </div>
                        <div>
                            <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Status</p>
                            <div class="mt-1.5">
                                <span
                                    class="inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-bold tracking-wider capitalize 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',
                                    }"
                                >
                                    {{ loan.status }}
                                </span>
                            </div>
                        </div>
                    </div>

                    <div v-if="loan.status === 'approved' && Number(loan.remaining_balance) > 0" class="space-y-3 border-t border-slate-100 pt-6 dark:border-slate-800">
                        <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Manual Repayment Entry</p>
                        <p class="text-xs text-slate-500">Record a partial or full repayment made outside payroll processing.</p>
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-slate-600 dark:text-slate-300">Repayment Amount</label>
                            <input
                                v-model="manualRepaymentForm.amount"
                                type="number"
                                min="0.01"
                                :max="loan.remaining_balance"
                                step="0.01"
                                placeholder="e.g. 1000.00"
                                class="h-10 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="manualRepaymentForm.errors.amount" class="text-xs text-rose-500">{{ manualRepaymentForm.errors.amount }}</p>
                        </div>
                        <div class="space-y-2">
                            <label class="text-xs font-semibold text-slate-600 dark:text-slate-300">Note (Optional)</label>
                            <input
                                v-model="manualRepaymentForm.note"
                                type="text"
                                maxlength="255"
                                placeholder="Cash repayment, transfer, etc."
                                class="h-10 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="manualRepaymentForm.errors.note" class="text-xs text-rose-500">{{ manualRepaymentForm.errors.note }}</p>
                        </div>
                        <Button @click="submitManualRepayment" :disabled="manualRepaymentForm.processing" class="w-full">
                            <span class="inline-flex items-center gap-2">
                                <Banknote class="h-4 w-4" />
                                {{ manualRepaymentForm.processing ? 'Saving...' : 'Record Repayment' }}
                            </span>
                        </Button>
                    </div>

                    <div class="border-t border-slate-100 pt-6 dark:border-slate-800" v-if="loan.approver">
                        <p class="text-xs font-bold tracking-wider text-slate-400 uppercase">Approved By</p>
                        <div class="mt-2 flex items-center gap-3">
                            <div
                                class="flex h-8 w-8 items-center justify-center rounded-full bg-slate-100 text-[10px] font-bold text-slate-500 uppercase"
                            >
                                {{ loan.approver.name.substring(0, 2) }}
                            </div>
                            <div>
                                <p class="text-sm leading-none font-bold text-slate-700 dark:text-slate-200">{{ loan.approver.name }}</p>
                                <p class="mt-1 text-[10px] text-slate-400" v-if="loan.approved_at">
                                    {{ new Date(loan.approved_at).toLocaleString() }}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transactions Ledger -->
                <div
                    class="overflow-hidden rounded-[2rem] border border-slate-200 bg-white shadow-sm lg:col-span-2 dark:border-slate-800 dark:bg-slate-900"
                >
                    <div class="border-b border-slate-100 p-6 dark:border-slate-800">
                        <h3 class="text-lg font-bold text-slate-800 dark:text-white">Amortization / Ledger</h3>
                        <p class="mt-1 text-sm text-slate-500">A history of all payroll deductions applied against this loan.</p>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead>
                                <tr
                                    class="border-b border-slate-100 bg-slate-50/50 text-xs font-bold tracking-wider text-slate-500 uppercase dark:border-slate-800 dark:bg-slate-800/50"
                                >
                                    <th class="px-6 py-4 text-left">Date</th>
                                    <th class="px-6 py-4 text-left">Source</th>
                                    <th class="px-6 py-4 text-left">Payroll Month</th>
                                    <th class="px-6 py-4 text-right">Deduction applied</th>
                                    <th class="px-6 py-4 text-right">Remaining Balance</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                                <tr
                                    v-for="transaction in loan.transactions"
                                    :key="transaction.id"
                                    class="group transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/50"
                                >
                                    <td class="px-6 py-4 font-medium text-slate-500">
                                        {{ new Date(transaction.created_at).toLocaleDateString() }}
                                    </td>
                                    <td class="px-6 py-4">
                                        <span
                                            class="inline-flex items-center rounded-lg px-2 py-0.5 text-[10px] font-bold tracking-wide uppercase"
                                            :class="
                                                transaction.source === 'manual'
                                                    ? 'bg-amber-50 text-amber-700'
                                                    : 'bg-indigo-50 text-indigo-600'
                                            "
                                        >
                                            {{ transaction.source === 'manual' ? 'Manual' : 'Payroll' }}
                                        </span>
                                        <p v-if="transaction.source === 'manual' && transaction.recorder?.name" class="mt-1 text-[10px] text-slate-400">
                                            by {{ transaction.recorder.name }}
                                        </p>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span
                                            v-if="transaction.payroll"
                                            class="inline-block rounded-lg bg-indigo-50 px-2 py-0.5 text-[10px] font-bold tracking-wide text-indigo-600 uppercase"
                                        >
                                            {{ transaction.payroll.month_year }}
                                        </span>
                                        <span v-else class="text-xs text-slate-400 italic">-</span>
                                        <p v-if="transaction.note" class="mt-1 text-[10px] text-slate-400">{{ transaction.note }}</p>
                                    </td>
                                    <td class="px-6 py-4 text-right font-bold text-emerald-500">-{{ formatMoney(transaction.deducted_amount) }}</td>
                                    <td class="px-6 py-4 text-right font-bold text-slate-700 dark:text-slate-200">
                                        {{ formatMoney(transaction.remaining_after) }}
                                    </td>
                                </tr>

                                <tr v-if="loan.transactions.length === 0">
                                    <td colspan="5" class="px-6 py-16 text-center">
                                        <div class="mx-auto max-w-xs space-y-2">
                                            <p class="text-sm font-medium text-slate-400 italic">No deductions have been made yet.</p>
                                            <p class="text-xs leading-relaxed text-slate-400">
                                                Installments are posted to this ledger when payroll is approved, or when a manual repayment is recorded.
                                            </p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
