import { Head, Link } from '@inertiajs/react';
import { HandCoins, Pencil, Plus } from 'lucide-react';
import EmptyState from '@/components/member/empty-state';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import { formatNaira, formatRate } from '@/lib/format';
import { cn } from '@/lib/utils';
import { create, edit, index } from '@/routes/admin/loan-products';
import type { LoanProduct } from '@/types';

type Quote = {
    principal: number;
    months: number;
    interest: number;
    processingFee: number;
    managementFee: number;
    totalRepayable: number;
    monthlyInstalment: number;
};

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

export default function LoanProductsIndex({
    products,
    canManage,
}: {
    products: (LoanProduct & { example: Quote })[];
    canManage: boolean;
}) {
    const newButton = canManage ? (
        <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"
        >
            <Plus className="size-4" />
            New product
        </Link>
    ) : undefined;

    return (
        <>
            <Head title="Loan products" />

            <MemberPage
                title="Loan products"
                description="The loans members can apply for, with their limits, fees, penalties and eligibility."
                actions={newButton}
            >
                {products.length === 0 ? (
                    <EmptyState
                        icon={HandCoins}
                        title="No loan products yet"
                        description="Add products such as Emergency, Business, Salary, School fees, Agricultural, Personal, Smart Save and Group loans."
                        action={newButton}
                    />
                ) : (
                    <ul className="grid grid-cols-1 gap-3 lg:grid-cols-2">
                        {products.map((product) => (
                            <li
                                key={product.id}
                                className={cn(
                                    'flex flex-col gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm',
                                    !product.isActive && 'opacity-70',
                                )}
                            >
                                <div className="flex items-start gap-3">
                                    <span className="flex size-10 shrink-0 items-center justify-center rounded-landing bg-brand-faint text-brand">
                                        <HandCoins className="size-5" />
                                    </span>
                                    <div className="min-w-0 flex-1">
                                        <p className="flex flex-wrap items-center gap-1.5 font-semibold text-ink">
                                            {product.name}
                                            {product.forGroups && (
                                                <StatusBadge tone="info">
                                                    Group loan
                                                </StatusBadge>
                                            )}
                                            {!product.isActive && (
                                                <StatusBadge tone="neutral">
                                                    Hidden
                                                </StatusBadge>
                                            )}
                                        </p>
                                        <p className="text-xs text-ink-400">
                                            {product.categoryLabel}
                                        </p>
                                    </div>
                                    {canManage && (
                                        <Link
                                            href={edit(product.id)}
                                            className="rounded-full p-1.5 text-ink-400 hover:bg-surface-100 hover:text-ink"
                                            aria-label={`Edit ${product.name}`}
                                        >
                                            <Pencil className="size-4" />
                                        </Link>
                                    )}
                                </div>

                                {product.description && (
                                    <p className="text-sm text-ink-700">
                                        {product.description}
                                    </p>
                                )}

                                <dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-3">
                                    <Fact term="Amount">
                                        {formatNaira(product.minAmount)} –{' '}
                                        {formatNaira(product.maxAmount)}
                                    </Fact>
                                    <Fact term="Term">
                                        {product.minTermMonths ===
                                        product.maxTermMonths
                                            ? months(product.maxTermMonths)
                                            : `${product.minTermMonths}–${months(product.maxTermMonths)}`}
                                    </Fact>
                                    {product.interestRate > 0 && (
                                        <Fact term="Interest">
                                            {formatRate(product.interestRate)} a
                                            month
                                        </Fact>
                                    )}
                                    <Fact term="Processing fee">
                                        {formatRate(product.processingFee)}
                                    </Fact>
                                    <Fact term="Management fee">
                                        {formatRate(product.managementFee)}
                                    </Fact>
                                    <Fact term="Late penalty">
                                        {formatRate(product.penaltyRate)} a
                                        month
                                        {product.graceDays > 0 &&
                                            ` after ${product.graceDays} days`}
                                    </Fact>
                                    <Fact term="Guarantors">
                                        {product.guarantorsRequired}
                                    </Fact>
                                </dl>

                                <p className="rounded-landing bg-surface-50 px-3 py-2 text-xs text-ink-500">
                                    Eligible after{' '}
                                    {months(product.minMembershipMonths)} of
                                    membership
                                    {product.minSavings > 0 &&
                                        ` with at least ${formatNaira(product.minSavings)} saved`}
                                    .
                                    {product.eligibilityNotes &&
                                        ` ${product.eligibilityNotes}`}
                                </p>

                                <p className="border-t border-surface-100 pt-3 text-xs text-ink-500">
                                    Example: borrow{' '}
                                    {formatNaira(product.example.principal)}{' '}
                                    over {months(product.example.months)} → pay{' '}
                                    <span className="font-semibold text-ink">
                                        {formatNaira(
                                            product.example.monthlyInstalment,
                                        )}
                                    </span>{' '}
                                    a month,{' '}
                                    {formatNaira(
                                        product.example.totalRepayable,
                                    )}{' '}
                                    in total
                                    {product.example.interest > 0 &&
                                        ` (interest ${formatNaira(product.example.interest)})`}
                                    , plus a{' '}
                                    {formatNaira(product.example.processingFee)}{' '}
                                    processing fee
                                    {product.example.managementFee > 0 &&
                                        ` and a ${formatNaira(product.example.managementFee)} management fee`}
                                    .
                                </p>
                            </li>
                        ))}
                    </ul>
                )}
            </MemberPage>
        </>
    );
}

function Fact({ term, children }: { term: string; children: React.ReactNode }) {
    return (
        <div className="min-w-0">
            <dt className="text-xs text-ink-400">{term}</dt>
            <dd className="font-semibold text-ink-700 tabular-nums">
                {children}
            </dd>
        </div>
    );
}

LoanProductsIndex.layout = {
    breadcrumbs: [{ title: 'Loan products', href: index() }],
};
