import { Head, Link } from '@inertiajs/react';
import { ArrowRight, HandCoins, ShieldAlert } from 'lucide-react';
import EmptyState from '@/components/member/empty-state';
import LoanStatus from '@/components/member/loan-status';
import MemberPage from '@/components/member/member-page';
import { formatDate, formatNaira, formatRate } from '@/lib/format';
import { show as kycShow } from '@/routes/kyc';
import { create, index, show } from '@/routes/loans';
import type { LoanItem, LoanProduct } from '@/types';

const wholeNairaFormatter = new Intl.NumberFormat('en-NG', {
    style: 'currency',
    currency: 'NGN',
    maximumFractionDigits: 0,
});

/** Naira without kobo, for headline amounts like ₦1,000,000. */
function wholeNaira(kobo: number): string {
    return wholeNairaFormatter.format(Math.round(kobo / 100));
}

function months(count: number): string {
    return `${count} ${count === 1 ? 'month' : 'months'}`;
}

export default function LoansIndex({
    loans,
    products,
    hasOpenLoan,
    isVerified,
}: {
    loans: LoanItem[];
    products: LoanProduct[];
    hasOpenLoan: boolean;
    isVerified: boolean;
}) {
    const canApply = isVerified && !hasOpenLoan;

    return (
        <>
            <Head title="Loans" />

            <MemberPage
                title="Loans"
                description="Apply for a loan and follow your application from review to disbursement."
                actions={
                    canApply &&
                    products.length > 0 && (
                        <Link
                            href={create()}
                            className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
                        >
                            <HandCoins className="size-4" />
                            Apply for a loan
                        </Link>
                    )
                }
            >
                {!isVerified && (
                    <section className="flex flex-wrap items-center gap-3 rounded-landing-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                        <ShieldAlert className="size-5 shrink-0" />
                        <p className="min-w-0 flex-1">
                            Verify your identity before you apply for a loan.
                        </p>
                        <Link
                            href={kycShow()}
                            className="font-semibold underline-offset-2 hover:underline"
                        >
                            Verify now
                        </Link>
                    </section>
                )}

                {loans.length > 0 && (
                    <section className="rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
                        <h2 className="border-b border-surface-100 px-5 py-4 font-display text-base font-semibold text-ink">
                            My loans
                        </h2>
                        <ul className="divide-y divide-surface-100">
                            {loans.map((loan) => (
                                <li key={loan.id}>
                                    <Link
                                        href={show(loan.id)}
                                        className="flex items-center gap-3 px-5 py-3 hover:bg-surface-50"
                                    >
                                        <span className="min-w-0 flex-1">
                                            <span className="block truncate font-semibold text-ink">
                                                {loan.productName}
                                            </span>
                                            <span className="block truncate text-xs text-ink-400">
                                                <span className="font-mono">
                                                    {loan.number}
                                                </span>{' '}
                                                · {formatDate(loan.createdAt)}
                                                {loan.groupName &&
                                                    ` · Group: ${loan.groupName}`}
                                            </span>
                                        </span>
                                        <span className="text-right">
                                            <span className="block font-semibold text-ink tabular-nums">
                                                {formatNaira(loan.amount)}
                                            </span>
                                            <LoanStatus
                                                status={loan.status}
                                                label={loan.statusLabel}
                                            />
                                        </span>
                                    </Link>
                                </li>
                            ))}
                        </ul>
                    </section>
                )}

                <section className="grid gap-3">
                    <h2 className="font-display text-base font-semibold text-ink">
                        Loans we offer
                    </h2>
                    {products.length === 0 ? (
                        <EmptyState
                            icon={HandCoins}
                            title="No loans on offer right now"
                            description="Please check back later or ask at the office."
                        />
                    ) : (
                        <ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
                            {products.map((product) => {
                                const terms = [
                                    `${formatRate(product.processingFee)} processing fee`,
                                    product.managementFee > 0 &&
                                        `${formatRate(product.managementFee)} management fee`,
                                    product.interestRate > 0 &&
                                        `${formatRate(product.interestRate)} interest a month`,
                                    product.guarantorsRequired > 0
                                        ? `${product.guarantorsRequired} guarantor${product.guarantorsRequired === 1 ? '' : 's'}`
                                        : 'No guarantor',
                                    product.minMembershipMonths > 0 &&
                                        `${months(product.minMembershipMonths)} membership`,
                                    product.minSavings > 0 &&
                                        `${wholeNaira(product.minSavings)} saved`,
                                ].filter(Boolean) as string[];

                                return (
                                    <li
                                        key={product.id}
                                        className="group flex flex-col overflow-hidden rounded-landing-lg border border-brand-border border-t-4 border-t-brand bg-white shadow-landing-lg transition hover:-translate-y-0.5 hover:shadow-landing-xl"
                                    >
                                        <div className="flex flex-1 flex-col gap-3 p-4">
                                            <div className="flex items-center gap-2.5">
                                                <span className="flex size-9 shrink-0 items-center justify-center rounded-landing bg-brand text-white">
                                                    <HandCoins className="size-4" />
                                                </span>
                                                <div className="min-w-0 flex-1">
                                                    <h3 className="truncate text-[15px] leading-tight font-semibold text-ink">
                                                        {product.name}
                                                    </h3>
                                                    <p className="truncate text-[11px] text-ink-400">
                                                        {product.categoryLabel}
                                                    </p>
                                                </div>
                                            </div>

                                            <div className="flex items-baseline justify-between gap-2 rounded-landing bg-brand-faint px-3 py-2">
                                                <span className="truncate text-sm font-semibold text-ink tabular-nums">
                                                    {wholeNaira(
                                                        product.minAmount,
                                                    )}{' '}
                                                    –{' '}
                                                    {wholeNaira(
                                                        product.maxAmount,
                                                    )}
                                                </span>
                                                <span className="shrink-0 text-xs font-medium text-ink-500">
                                                    {product.minTermMonths ===
                                                    product.maxTermMonths
                                                        ? months(
                                                              product.maxTermMonths,
                                                          )
                                                        : `${product.minTermMonths}–${months(product.maxTermMonths)}`}
                                                </span>
                                            </div>

                                            <ul className="flex flex-wrap gap-1">
                                                {terms.map((term) => (
                                                    <li
                                                        key={term}
                                                        className="rounded-full bg-surface-100 px-2 py-0.5 text-[11px] font-medium text-ink-700"
                                                    >
                                                        {term}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>

                                        {canApply && (
                                            <Link
                                                href={create({
                                                    query: {
                                                        product: product.id,
                                                    },
                                                })}
                                                className="flex items-center justify-center gap-1.5 bg-brand px-4 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-brand-hover"
                                            >
                                                Apply
                                                <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
                                            </Link>
                                        )}
                                    </li>
                                );
                            })}
                        </ul>
                    )}
                </section>
            </MemberPage>
        </>
    );
}

LoansIndex.layout = {
    breadcrumbs: [{ title: 'Loans', href: index() }],
};
