import { Head, Link } from '@inertiajs/react';
import LoanStatus from '@/components/member/loan-status';
import MemberPage from '@/components/member/member-page';
import ReportToolbar from '@/components/report-toolbar';
import { formatDate, formatNaira } from '@/lib/format';
import { show as loanShow } from '@/routes/admin/loans';
import { index, loans } from '@/routes/admin/reports';
import type { SelectOption } from '@/types';

type Row = {
    id: number;
    date: string | null;
    number: string;
    member: string;
    memberId: string;
    product: string;
    amount: number;
    status: string;
    statusLabel: string;
    outstanding: number;
    overdue: number;
    daysOverdue: number;
    reference: string | null;
    recordedBy: string | null;
    note: string | null;
};

export default function LoanReport({
    report,
    reports,
    filters,
    rows,
    totals,
    branches,
}: {
    report: string;
    reports: SelectOption[];
    filters: Record<string, string>;
    rows: Row[];
    totals: {
        count: number;
        amount: number;
        outstanding: number;
        overdue: number;
    };
    branches: SelectOption[];
}) {
    const isBook = report === 'outstanding' || report === 'overdue';
    const title =
        reports.find((option) => option.value === report)?.label ?? 'Loans';

    return (
        <>
            <Head title={`Loan report · ${title}`} />

            <MemberPage
                title={`Loan report · ${title}`}
                description={
                    isBook
                        ? 'Loans being repaid today.'
                        : `${formatDate(filters.from)} – ${formatDate(filters.to)}`
                }
            >
                <ReportToolbar
                    filters={{ ...filters, report }}
                    selects={[
                        { name: 'report', label: 'Report', options: reports },
                        {
                            name: 'branch',
                            label: 'Branch',
                            options: branches,
                            allLabel: 'All branches',
                        },
                    ]}
                    downloads={[{ label: 'Download' }]}
                />

                <section className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                    <Figure label="Loans" value={String(totals.count)} />
                    <Figure
                        label={report === 'repayments' ? 'Repaid' : 'Amount'}
                        value={formatNaira(totals.amount)}
                    />
                    {isBook && (
                        <>
                            <Figure
                                label="Outstanding"
                                value={formatNaira(totals.outstanding)}
                            />
                            <Figure
                                label="Overdue"
                                value={formatNaira(totals.overdue)}
                            />
                        </>
                    )}
                </section>

                <section className="overflow-x-auto rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
                    {rows.length === 0 ? (
                        <p className="p-4 text-sm text-ink-400">
                            Nothing to show for these filters.
                        </p>
                    ) : (
                        <table className="w-full min-w-[720px] text-sm">
                            <thead>
                                <tr className="border-b border-surface-100 text-left text-xs text-ink-400">
                                    <th className="px-4 py-2 font-semibold">
                                        Date
                                    </th>
                                    <th className="px-4 py-2 font-semibold">
                                        Loan
                                    </th>
                                    <th className="px-4 py-2 text-right font-semibold">
                                        {report === 'repayments'
                                            ? 'Repaid'
                                            : 'Amount'}
                                    </th>
                                    {isBook && (
                                        <>
                                            <th className="px-4 py-2 text-right font-semibold">
                                                Outstanding
                                            </th>
                                            <th className="px-4 py-2 text-right font-semibold">
                                                Overdue
                                            </th>
                                        </>
                                    )}
                                    <th className="px-4 py-2 font-semibold">
                                        {report === 'repayments'
                                            ? 'Recorded by'
                                            : 'Status'}
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-surface-100 tabular-nums">
                                {rows.map((row, position) => (
                                    <tr key={`${row.id}-${position}`}>
                                        <td className="px-4 py-2 whitespace-nowrap text-ink-500">
                                            {formatDate(row.date)}
                                        </td>
                                        <td className="px-4 py-2">
                                            <Link
                                                href={loanShow(row.id)}
                                                className="block font-semibold text-ink hover:text-brand"
                                            >
                                                {row.member}
                                            </Link>
                                            <span className="block text-xs text-ink-400">
                                                <span className="font-mono">
                                                    {row.reference ??
                                                        row.number}
                                                </span>{' '}
                                                · {row.product}
                                                {row.note && ` · ${row.note}`}
                                            </span>
                                        </td>
                                        <td className="px-4 py-2 text-right font-semibold text-ink">
                                            {formatNaira(row.amount)}
                                        </td>
                                        {isBook && (
                                            <>
                                                <td className="px-4 py-2 text-right">
                                                    {formatNaira(
                                                        row.outstanding,
                                                    )}
                                                </td>
                                                <td className="px-4 py-2 text-right text-red-700">
                                                    {row.overdue > 0
                                                        ? `${formatNaira(row.overdue)} · ${row.daysOverdue}d`
                                                        : '—'}
                                                </td>
                                            </>
                                        )}
                                        <td className="px-4 py-2">
                                            {report === 'repayments' ? (
                                                <span className="text-xs text-ink-500">
                                                    {row.recordedBy}
                                                </span>
                                            ) : (
                                                <LoanStatus
                                                    status={row.status}
                                                    label={row.statusLabel}
                                                />
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </section>
            </MemberPage>
        </>
    );
}

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

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