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

type Amounts = {
    deposits: number;
    intoPlans: number;
    fromPlans: number;
    withdrawals: number;
};

const amountColumns: { key: keyof Amounts; label: string }[] = [
    { key: 'deposits', label: 'Deposits' },
    { key: 'intoPlans', label: 'Into savings plans' },
    { key: 'fromPlans', label: 'From savings plans' },
    { key: 'withdrawals', label: 'Withdrawals' },
];

export default function SavingsReport({
    filters,
    periods,
    members,
    totals,
    frequencies,
    branches,
    groups,
    memberName,
}: {
    filters: Record<string, string>;
    periods: (Amounts & { start: string; label: string })[];
    members: (Amounts & { id: number; name: string; memberId: string })[];
    totals: Amounts;
    frequencies: SelectOption[];
    branches: SelectOption[];
    groups: SelectOption[];
    memberName: string | null;
}) {
    return (
        <>
            <Head title="Savings report" />

            <MemberPage
                title="Savings report"
                description={`${formatDate(filters.from)} – ${formatDate(filters.to)}${memberName ? ` · ${memberName}` : ''}`}
            >
                <ReportToolbar
                    filters={filters}
                    selects={[
                        { name: 'by', label: 'Per', options: frequencies },
                        {
                            name: 'branch',
                            label: 'Branch',
                            options: branches,
                            allLabel: 'All branches',
                        },
                        {
                            name: 'group',
                            label: 'Group',
                            options: groups,
                            allLabel: 'All groups',
                        },
                    ]}
                    downloads={[
                        { label: 'By period', query: { table: 'periods' } },
                        { label: 'By member', query: { table: 'members' } },
                    ]}
                />

                <section className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                    {amountColumns.map((column) => (
                        <div
                            key={column.key}
                            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">
                                {column.label}
                            </p>
                            <p className="mt-1 font-display text-lg font-semibold text-ink tabular-nums">
                                {formatNaira(totals[column.key])}
                            </p>
                        </div>
                    ))}
                </section>

                <AmountTable
                    title="By period"
                    firstHeading="Period"
                    rows={periods.map((row) => ({
                        key: row.start,
                        first: row.label,
                        amounts: row,
                    }))}
                    totals={totals}
                />

                <AmountTable
                    title="By member"
                    firstHeading="Member"
                    rows={members.map((row) => ({
                        key: String(row.id),
                        first: (
                            <Link
                                href={userShow(row.id)}
                                className="hover:text-brand"
                            >
                                {row.name}{' '}
                                <span className="font-mono text-xs text-ink-400">
                                    {row.memberId}
                                </span>
                            </Link>
                        ),
                        amounts: row,
                    }))}
                    totals={totals}
                />
            </MemberPage>
        </>
    );
}

function AmountTable({
    title,
    firstHeading,
    rows,
    totals,
}: {
    title: string;
    firstHeading: string;
    rows: { key: string; first: React.ReactNode; amounts: Amounts }[];
    totals: Amounts;
}) {
    return (
        <section className="overflow-x-auto rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
            <h2 className="px-4 pt-4 font-display text-base font-semibold text-ink">
                {title}
            </h2>
            {rows.length === 0 ? (
                <p className="px-4 py-4 text-sm text-ink-400">
                    No savings activity in this period.
                </p>
            ) : (
                <table className="mt-2 w-full min-w-[640px] 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">
                                {firstHeading}
                            </th>
                            {amountColumns.map((column) => (
                                <th
                                    key={column.key}
                                    className="px-4 py-2 text-right font-semibold"
                                >
                                    {column.label}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-surface-100 tabular-nums">
                        {rows.map((row) => (
                            <tr key={row.key}>
                                <td className="px-4 py-2 font-semibold text-ink">
                                    {row.first}
                                </td>
                                {amountColumns.map((column) => (
                                    <td
                                        key={column.key}
                                        className="px-4 py-2 text-right"
                                    >
                                        {formatNaira(row.amounts[column.key])}
                                    </td>
                                ))}
                            </tr>
                        ))}
                    </tbody>
                    <tfoot>
                        <tr className="border-t-2 border-surface-200 font-semibold text-ink tabular-nums">
                            <td className="px-4 py-2">Total</td>
                            {amountColumns.map((column) => (
                                <td
                                    key={column.key}
                                    className="px-4 py-2 text-right"
                                >
                                    {formatNaira(totals[column.key])}
                                </td>
                            ))}
                        </tr>
                    </tfoot>
                </table>
            )}
        </section>
    );
}

SavingsReport.layout = {
    breadcrumbs: [
        { title: 'Reports', href: index() },
        { title: 'Savings', href: savings() },
    ],
};
