import { Head, Link } from '@inertiajs/react';
import { HandCoins, ShieldAlert, UsersRound } 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, groups as groupsRoute, show } from '@/routes/loans';
import type { LoanItem, LoanProduct } from '@/types';

type LedGroup = {
    id: number;
    name: string;
    memberCount: number;
    hasOpenLoan: boolean;
};

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

/**
 * Group loans: a Smart Save group's leader applies for one loan on the
 * group's behalf. It is paid to and repaid by the leader, and every
 * member is jointly responsible.
 */
export default function GroupLoans({
    ledGroups,
    groupCount,
    canStartGroup,
    loans,
    products,
    isVerified,
}: {
    ledGroups: LedGroup[];
    groupCount: number;
    canStartGroup: boolean;
    loans: LoanItem[];
    products: LoanProduct[];
    isVerified: boolean;
}) {
    return (
        <>
            <Head title="Group loans" />

            <MemberPage
                title="Group loans"
                description="One loan for your Smart Save group. Whoever applies becomes the group's leader, receives and repays the loan, and every member is jointly responsible."
                actions={
                    isVerified &&
                    canStartGroup &&
                    products.length > 0 && (
                        <Link
                            href={create({ query: { group: 'new' } })}
                            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 group 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 group
                            loan.
                        </p>
                        <Link
                            href={kycShow()}
                            className="font-semibold underline-offset-2 hover:underline"
                        >
                            Verify now
                        </Link>
                    </section>
                )}

                {ledGroups.length > 0 && (
                    <section className="rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
                        <div className="border-b border-surface-100 px-5 py-4">
                            <h2 className="font-display text-base font-semibold text-ink">
                                Groups you lead
                            </h2>
                            <p className="text-xs text-ink-400">
                                Apply for one loan at a time for each group.
                            </p>
                        </div>
                        <ul className="divide-y divide-surface-100">
                            {ledGroups.map((group) => (
                                <li
                                    key={group.id}
                                    className="flex flex-wrap items-center gap-3 px-5 py-3"
                                >
                                    <span className="flex size-9 shrink-0 items-center justify-center rounded-landing bg-brand-faint text-brand">
                                        <UsersRound className="size-4" />
                                    </span>
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate font-semibold text-ink">
                                            {group.name}
                                        </span>
                                        <span className="block text-xs text-ink-400">
                                            {group.memberCount}{' '}
                                            {group.memberCount === 1
                                                ? 'member'
                                                : 'members'}
                                        </span>
                                    </span>
                                    {group.hasOpenLoan ? (
                                        <span className="text-xs text-ink-500">
                                            Loan already open
                                        </span>
                                    ) : group.memberCount < 2 ? (
                                        <span className="text-xs text-ink-500">
                                            Needs at least 2 members
                                        </span>
                                    ) : products.length === 0 ? (
                                        <span className="text-xs text-ink-500">
                                            No group loans on offer yet
                                        </span>
                                    ) : isVerified ? (
                                        <Link
                                            href={create({
                                                query: { group: group.id },
                                            })}
                                            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 group loan
                                        </Link>
                                    ) : null}
                                </li>
                            ))}
                        </ul>
                    </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">
                            Your groups' 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.groupName}
                                            </span>
                                            <span className="block truncate text-xs text-ink-400">
                                                <span className="font-mono">
                                                    {loan.number}
                                                </span>{' '}
                                                · {loan.productName} ·{' '}
                                                {formatDate(loan.createdAt)}
                                            </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>
                )}

                {ledGroups.length === 0 && loans.length === 0 && (
                    <EmptyState
                        icon={UsersRound}
                        title="No group loans yet"
                        description={
                            products.length === 0
                                ? 'No group loans are on offer right now. Please check back later.'
                                : `Apply for a group loan, add the members of your group, and you become its leader.${groupCount > 0 ? ' Loans of groups you belong to will also show here.' : ''}`
                        }
                        action={
                            isVerified &&
                            canStartGroup &&
                            products.length > 0 && (
                                <Link
                                    href={create({ query: { group: 'new' } })}
                                    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 group loan
                                </Link>
                            )
                        }
                    />
                )}

                {products.length > 0 && (
                    <section className="grid gap-3">
                        <h2 className="font-display text-base font-semibold text-ink">
                            Group loans we offer
                        </h2>
                        <ul className="grid grid-cols-1 gap-3 md:grid-cols-2">
                            {products.map((product) => (
                                <li
                                    key={product.id}
                                    className="flex flex-col gap-2 rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm"
                                >
                                    <p className="font-semibold text-ink">
                                        {product.name}
                                    </p>
                                    {product.description && (
                                        <p className="text-sm text-ink-700">
                                            {product.description}
                                        </p>
                                    )}
                                    <p className="text-xs text-ink-500">
                                        {formatNaira(product.minAmount)} –{' '}
                                        {formatNaira(product.maxAmount)} over{' '}
                                        {product.minTermMonths}–
                                        {months(product.maxTermMonths)} ·
                                        processing fee{' '}
                                        {formatRate(product.processingFee)}
                                        {product.managementFee > 0 &&
                                            ` · management fee ${formatRate(product.managementFee)}`}
                                        {product.interestRate > 0 &&
                                            ` · interest ${formatRate(product.interestRate)} a month`}
                                    </p>
                                </li>
                            ))}
                        </ul>
                    </section>
                )}
            </MemberPage>
        </>
    );
}

GroupLoans.layout = {
    breadcrumbs: [{ title: 'Group loans', href: groupsRoute() }],
};
