import { FileText, UserCheck, UsersRound } from 'lucide-react';
import type { ReactNode } from 'react';
import StatusBadge from '@/components/member/status-badge';
import { formatDateTime, formatNaira, formatRate } from '@/lib/format';
import type { LoanDetails as Loan } from '@/types';

function fileSize(bytes: number): string {
    return bytes >= 1024 * 1024
        ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
        : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}

/**
 * Everything on a loan application: cost, the member's answers,
 * guarantors and supporting documents.
 */
export default function LoanDetails({
    loan,
    guarantorActions,
}: {
    loan: Loan;
    guarantorActions?: (guarantor: Loan['guarantors'][number]) => ReactNode;
}) {
    return (
        <div className="grid gap-5">
            <section className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                <Figure label="Amount" value={formatNaira(loan.amount)} />
                <Figure
                    label="Monthly instalment"
                    value={formatNaira(loan.monthlyInstalment)}
                    hint={`${loan.termMonths} months`}
                />
                <Figure
                    label="Total to repay"
                    value={formatNaira(loan.totalRepayable)}
                    hint={
                        loan.interest > 0
                            ? `Interest ${formatNaira(loan.interest)} at ${formatRate(loan.interestRate)} a month`
                            : undefined
                    }
                />
                <Figure
                    label="Processing fee"
                    value={formatNaira(loan.processingFee)}
                    hint={`${formatRate(loan.processingFeeRate)} once`}
                />
                {loan.managementFee > 0 && (
                    <Figure
                        label="Management fee"
                        value={formatNaira(loan.managementFee)}
                        hint={`${formatRate(loan.managementFeeRate)} once`}
                    />
                )}
            </section>

            <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                <h2 className="font-display text-base font-semibold text-ink">
                    Application
                </h2>
                <dl className="mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2">
                    <Item term="Loan type">
                        {loan.productName} · {loan.categoryLabel}
                    </Item>
                    {loan.group && (
                        <Item term="Group">
                            {loan.group.name} · {loan.group.accountNumber}
                            {loan.group.leaderName &&
                                ` · led by ${loan.group.leaderName}`}
                        </Item>
                    )}
                    <Item term="Applied">{formatDateTime(loan.createdAt)}</Item>
                    <Item term="Monthly income">
                        {formatNaira(loan.monthlyIncome)}
                    </Item>
                    <Item term="Late penalty">
                        {formatRate(loan.penaltyRate)} of an overdue instalment
                        a month
                        {loan.graceDays > 0 && `, after ${loan.graceDays} days`}
                    </Item>
                    <Item term="Purpose" wide>
                        <span className="whitespace-pre-line">
                            {loan.purpose}
                        </span>
                    </Item>
                    <Item term="Existing loans" wide>
                        {loan.existingLoans ?? 'None'}
                    </Item>
                </dl>
            </section>

            <div className="grid gap-5 lg:grid-cols-2">
                <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                    <h2 className="font-display text-base font-semibold text-ink">
                        {loan.group ? 'Jointly responsible' : 'Guarantors'}
                    </h2>
                    {loan.group ? (
                        <>
                            <p className="mt-1 text-xs text-ink-400">
                                A group loan needs no guarantors. Every member
                                of {loan.group.name} is jointly responsible for
                                repaying it.
                            </p>
                            <ul className="mt-3 divide-y divide-surface-100">
                                {loan.group.members.map((member) => (
                                    <li
                                        key={member.id}
                                        className="flex items-center gap-2 py-2 text-sm"
                                    >
                                        <UsersRound className="size-4 shrink-0 text-brand" />
                                        <span className="min-w-0 flex-1 truncate font-medium text-ink">
                                            {member.name}
                                        </span>
                                        <span className="font-mono text-xs text-ink-400">
                                            {member.memberId}
                                        </span>
                                    </li>
                                ))}
                                {loan.group.outsiders.map((outsider) => (
                                    <li
                                        key={`outsider-${outsider.id}`}
                                        className="flex items-start gap-3 py-2.5 text-sm"
                                    >
                                        <a
                                            href={outsider.photoUrl}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="shrink-0"
                                        >
                                            <img
                                                src={outsider.photoUrl}
                                                alt={`Photo of ${outsider.name}`}
                                                className="size-10 rounded-full border border-surface-200 object-cover"
                                            />
                                        </a>
                                        <span className="min-w-0 flex-1">
                                            <span className="flex flex-wrap items-center gap-1.5">
                                                <span className="truncate font-medium text-ink">
                                                    {outsider.name}
                                                </span>
                                                <StatusBadge tone="neutral">
                                                    Not on Smart Save
                                                </StatusBadge>
                                            </span>
                                            <span className="block font-mono text-xs text-ink-400">
                                                {outsider.phone} · BVN{' '}
                                                {outsider.bvn} · NIN{' '}
                                                {outsider.nin}
                                            </span>
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        </>
                    ) : loan.guarantors.length === 0 ? (
                        <p className="mt-2 text-sm text-ink-400">
                            No guarantor was needed.
                        </p>
                    ) : (
                        <ul className="mt-3 divide-y divide-surface-100">
                            {loan.guarantors.map((guarantor) => (
                                <li
                                    key={guarantor.id}
                                    className="flex gap-3 py-3"
                                >
                                    {guarantor.photoUrl ? (
                                        <img
                                            src={guarantor.photoUrl}
                                            alt={`Photo of ${guarantor.name}`}
                                            className="size-12 shrink-0 rounded-landing object-cover"
                                        />
                                    ) : (
                                        <span className="flex size-12 shrink-0 items-center justify-center rounded-landing bg-surface-100 text-ink-300">
                                            <UserCheck className="size-5" />
                                        </span>
                                    )}
                                    <div className="min-w-0 flex-1 text-sm">
                                        <p className="flex flex-wrap items-center gap-1.5 font-semibold text-ink">
                                            {guarantor.name}
                                            <StatusBadge
                                                tone={
                                                    guarantor.status ===
                                                    'verified'
                                                        ? 'success'
                                                        : guarantor.status ===
                                                            'rejected'
                                                          ? 'failed'
                                                          : 'pending'
                                                }
                                            >
                                                {guarantor.statusLabel}
                                            </StatusBadge>
                                        </p>
                                        <p className="text-xs text-ink-500">
                                            {guarantor.relationship} ·{' '}
                                            {guarantor.occupation} ·{' '}
                                            {guarantor.phone}
                                            {guarantor.memberId &&
                                                ` · ${guarantor.memberId}`}
                                        </p>
                                        <p className="text-xs text-ink-400">
                                            {guarantor.address}
                                        </p>
                                        <p className="text-xs text-ink-500">
                                            ID:{' '}
                                            {guarantor.idNumber ?? 'not given'}
                                        </p>
                                        {guarantor.signatureUrl && (
                                            <img
                                                src={guarantor.signatureUrl}
                                                alt={`Signature of ${guarantor.name}`}
                                                className="mt-1 h-10 max-w-40 rounded border border-surface-200 bg-white object-contain p-1"
                                            />
                                        )}
                                        {guarantorActions?.(guarantor)}
                                    </div>
                                </li>
                            ))}
                        </ul>
                    )}
                </section>

                <section className="rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
                    <h2 className="font-display text-base font-semibold text-ink">
                        Supporting documents
                    </h2>
                    {loan.documents.length === 0 ? (
                        <p className="mt-2 text-sm text-ink-400">
                            No documents attached.
                        </p>
                    ) : (
                        <ul className="mt-3 divide-y divide-surface-100">
                            {loan.documents.map((document) => (
                                <li key={document.id}>
                                    <a
                                        href={document.url}
                                        target="_blank"
                                        rel="noreferrer"
                                        className="flex items-center gap-3 py-2.5 text-sm hover:text-brand"
                                    >
                                        <FileText className="size-4 shrink-0 text-ink-400" />
                                        <span className="min-w-0 flex-1 truncate font-semibold text-ink-700">
                                            {document.name}
                                        </span>
                                        <span className="text-xs text-ink-400">
                                            {fileSize(document.size)}
                                        </span>
                                    </a>
                                </li>
                            ))}
                        </ul>
                    )}
                </section>
            </div>
        </div>
    );
}

function Figure({
    label,
    value,
    hint,
}: {
    label: string;
    value: string;
    hint?: string;
}) {
    return (
        <section className="min-w-0 rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm">
            <p className="truncate text-[11px] font-semibold tracking-widest text-ink-400 uppercase">
                {label}
            </p>
            <p className="mt-1 truncate font-display text-xl font-semibold text-ink tabular-nums">
                {value}
            </p>
            {hint && <p className="truncate text-xs text-ink-500">{hint}</p>}
        </section>
    );
}

function Item({
    term,
    wide = false,
    children,
}: {
    term: string;
    wide?: boolean;
    children: React.ReactNode;
}) {
    return (
        <div className={wide ? 'sm:col-span-2' : undefined}>
            <dt className="text-xs text-ink-400">{term}</dt>
            <dd className="mt-0.5 text-ink-700">{children}</dd>
        </div>
    );
}
