import type { ReactNode } from 'react';
import LoanStanding from '@/components/member/loan-standing';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { formatDate, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { LoanDetails } from '@/types';

const statusMeta: Record<string, { label: string; tone: BadgeTone }> = {
    paid: { label: 'Paid', tone: 'success' },
    overdue: { label: 'Overdue', tone: 'failed' },
    partial: { label: 'Part paid', tone: 'pending' },
    due: { label: 'Due today', tone: 'pending' },
    upcoming: { label: 'Upcoming', tone: 'neutral' },
};

/**
 * Repayment position and monthly schedule of a disbursed loan (AMCSMS §14).
 */
export default function LoanRepayment({
    loan,
    action,
}: {
    loan: LoanDetails;
    action?: ReactNode;
}) {
    const summary = loan.repayment;

    if (!summary) {
        return null;
    }

    return (
        <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 shadow-landing-sm">
            <div className="flex flex-wrap items-center justify-between gap-2">
                <h2 className="font-display text-base font-semibold text-ink">
                    Repayment
                </h2>
                {loan.status === 'disbursed' && (
                    <LoanStanding
                        standing={summary.standing}
                        label={summary.standingLabel}
                        daysOverdue={summary.daysOverdue}
                    />
                )}
            </div>

            <dl className="grid grid-cols-2 gap-3 text-sm lg:grid-cols-6">
                <Figure term="Paid" value={formatNaira(summary.amountPaid)} />
                <Figure
                    term="Outstanding"
                    value={formatNaira(summary.outstanding)}
                    strong
                />
                <Figure
                    term="Next payment"
                    value={
                        summary.nextDueDate
                            ? formatNaira(summary.nextDueAmount)
                            : '—'
                    }
                    hint={
                        summary.nextDueDate
                            ? `due ${formatDate(summary.nextDueDate)}`
                            : 'Nothing left to pay'
                    }
                />
                <Figure
                    term="Overdue"
                    value={formatNaira(summary.overdueAmount)}
                    danger={summary.overdueAmount > 0}
                />
                <Figure
                    term="Penalty"
                    value={formatNaira(summary.penaltyOutstanding)}
                    hint={`${formatNaira(summary.penaltyCharged)} charged in all`}
                    danger={summary.penaltyOutstanding > 0}
                />
                <Figure
                    term="Instalments left"
                    value={`${summary.remainingInstalments} of ${summary.totalInstalments}`}
                />
            </dl>

            {action}

            <div className="overflow-x-auto">
                <table className="w-full min-w-[640px] text-sm">
                    <thead>
                        <tr className="border-b border-surface-100 text-left text-xs text-ink-400">
                            <th className="py-2 pr-3 font-semibold">#</th>
                            <th className="py-2 pr-3 font-semibold">Due</th>
                            <th className="py-2 pr-3 text-right font-semibold">
                                Principal
                            </th>
                            <th className="py-2 pr-3 text-right font-semibold">
                                Interest
                            </th>
                            <th className="py-2 pr-3 text-right font-semibold">
                                Total
                            </th>
                            <th className="py-2 pr-3 text-right font-semibold">
                                Penalty
                            </th>
                            <th className="py-2 pr-3 text-right font-semibold">
                                Paid
                            </th>
                            <th className="py-2 font-semibold">Status</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-surface-100 tabular-nums">
                        {loan.instalments.map((instalment) => (
                            <tr
                                key={instalment.id}
                                className={cn(
                                    instalment.status === 'overdue' &&
                                        'bg-red-50/60',
                                )}
                            >
                                <td className="py-2 pr-3 text-ink-400">
                                    {instalment.sequence}
                                </td>
                                <td className="py-2 pr-3 whitespace-nowrap text-ink-700">
                                    {formatDate(instalment.dueDate)}
                                </td>
                                <td className="py-2 pr-3 text-right">
                                    {formatNaira(instalment.principal)}
                                </td>
                                <td className="py-2 pr-3 text-right">
                                    {formatNaira(instalment.interest)}
                                </td>
                                <td className="py-2 pr-3 text-right font-semibold text-ink">
                                    {formatNaira(instalment.amount)}
                                </td>
                                <td className="py-2 pr-3 text-right">
                                    {instalment.penalty > 0
                                        ? formatNaira(instalment.penalty)
                                        : '—'}
                                </td>
                                <td className="py-2 pr-3 text-right">
                                    {formatNaira(instalment.paid)}
                                </td>
                                <td className="py-2">
                                    <StatusBadge
                                        tone={
                                            statusMeta[instalment.status].tone
                                        }
                                    >
                                        {statusMeta[instalment.status].label}
                                    </StatusBadge>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </section>
    );
}

function Figure({
    term,
    value,
    hint,
    strong = false,
    danger = false,
}: {
    term: string;
    value: string;
    hint?: string;
    strong?: boolean;
    danger?: boolean;
}) {
    return (
        <div className="min-w-0 rounded-landing bg-surface-50 p-3">
            <dt className="text-xs text-ink-400">{term}</dt>
            <dd
                className={cn(
                    'truncate font-semibold tabular-nums',
                    strong ? 'text-lg text-ink' : 'text-ink-700',
                    danger && 'text-red-600',
                )}
            >
                {value}
            </dd>
            {hint && <p className="truncate text-xs text-ink-400">{hint}</p>}
        </div>
    );
}
