import { Head, Link, router } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    CalendarCheck,
    ChevronLeft,
    ChevronRight,
    CircleCheck,
    CircleDashed,
    CircleDot,
    Plus,
    Repeat,
} from 'lucide-react';
import { useState } from 'react';
import DataTable from '@/components/data-table';
import type { DataTableColumn } from '@/components/data-table';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import type { BadgeTone } from '@/components/member/status-badge';
import { Input } from '@/components/ui/input';
import { formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { index } from '@/routes/admin/contributions';
import { create as recordDeposit } from '@/routes/admin/deposits';
import { show as userShow } from '@/routes/admin/users';
import type { SelectOption } from '@/types';

type Row = {
    id: number;
    name: string;
    typeLabel: string;
    expected: number;
    paid: number;
    outstanding: number;
    status: 'paid' | 'partial' | 'pending';
    autoDebit: boolean;
    member: { id: number; name: string; memberId: string };
};

type Summary = {
    expected: number;
    collected: number;
    outstanding: number;
    plans: number;
    paid: number;
    partial: number;
    pending: number;
};

type Period = {
    frequency: string;
    date: string;
    start: string;
    end: string;
    label: string;
    previous: string;
    next: string;
};

const statusMeta: Record<
    Row['status'],
    { label: string; tone: BadgeTone; icon: LucideIcon }
> = {
    paid: { label: 'Paid', tone: 'success', icon: CircleCheck },
    partial: { label: 'Part paid', tone: 'pending', icon: CircleDot },
    pending: { label: 'Pending', tone: 'failed', icon: CircleDashed },
};

export default function Contributions({
    rows,
    summary,
    period,
    frequencies,
    canRecord,
}: {
    rows: Row[];
    summary: Summary;
    period: Period;
    frequencies: SelectOption[];
    canRecord: boolean;
}) {
    const [statusFilter, setStatusFilter] = useState<'all' | Row['status']>(
        'all',
    );
    const visibleRows =
        statusFilter === 'all'
            ? rows
            : rows.filter((row) => row.status === statusFilter);
    const collectedShare =
        summary.expected > 0
            ? Math.round((summary.collected * 100) / summary.expected)
            : 0;

    const visit = (frequency: string, date: string) =>
        router.get(
            index.url({ query: { frequency, date } }),
            {},
            { preserveScroll: true, preserveState: false },
        );

    const columns: DataTableColumn<Row>[] = [
        {
            key: 'member',
            header: 'Member',
            sortable: true,
            sortValue: (row) => row.member.name,
            cell: (row) => (
                <Link
                    href={userShow(row.member.id)}
                    className="group block min-w-0"
                >
                    <span className="block truncate font-semibold text-ink group-hover:text-brand">
                        {row.member.name}
                    </span>
                    <span className="block truncate font-mono text-xs text-ink-400">
                        {row.member.memberId}
                    </span>
                </Link>
            ),
        },
        {
            key: 'name',
            header: 'Plan',
            sortable: true,
            hideOnMobile: true,
            cell: (row) => (
                <span className="block min-w-0">
                    <span className="block truncate text-ink">{row.name}</span>
                    <span className="flex items-center gap-1 text-xs text-ink-400">
                        {row.typeLabel}
                        {row.autoDebit && (
                            <>
                                {' '}
                                · <Repeat className="size-3" /> auto
                            </>
                        )}
                    </span>
                </span>
            ),
        },
        {
            key: 'expected',
            header: 'Due',
            sortable: true,
            align: 'right',
            className: 'whitespace-nowrap tabular-nums',
            cell: (row) => formatNaira(row.expected),
        },
        {
            key: 'paid',
            header: 'Paid',
            sortable: true,
            align: 'right',
            className: 'whitespace-nowrap tabular-nums',
            cell: (row) => (
                <span
                    className={cn(
                        'font-semibold',
                        row.paid > 0 ? 'text-highlight-dark' : 'text-ink-300',
                    )}
                >
                    {formatNaira(row.paid)}
                </span>
            ),
        },
        {
            key: 'status',
            header: 'Status',
            sortable: true,
            sortValue: (row) =>
                ({ pending: 0, partial: 1, paid: 2 })[row.status],
            cell: (row) => {
                const meta = statusMeta[row.status];

                return (
                    <StatusBadge tone={meta.tone}>
                        <meta.icon className="mr-1 size-3" />
                        {meta.label}
                    </StatusBadge>
                );
            },
        },
        {
            key: 'actions',
            header: <span className="sr-only">Actions</span>,
            align: 'right',
            className: 'w-px whitespace-nowrap',
            cell: (row) =>
                canRecord && row.status !== 'paid' ? (
                    <Link
                        href={recordDeposit({
                            query: { member: row.member.id, plan: row.id },
                        })}
                        className="inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-sm font-semibold text-brand hover:bg-brand-faint"
                        aria-label={`Record ${row.member.name}'s contribution`}
                    >
                        <Plus className="size-3.5" />
                        Record
                    </Link>
                ) : null,
        },
    ];

    return (
        <>
            <Head title="Contributions" />

            <MemberPage
                title="Contributions"
                description="Who has paid their scheduled savings contribution for the period."
            >
                <section className="flex flex-wrap items-center gap-3 rounded-landing-lg border border-surface-200 bg-white p-3 shadow-landing-sm">
                    <div
                        role="tablist"
                        aria-label="Contribution frequency"
                        className="inline-flex gap-1 rounded-full bg-surface-100 p-1"
                    >
                        {frequencies.map((frequency) => (
                            <button
                                key={frequency.value}
                                type="button"
                                role="tab"
                                aria-selected={
                                    period.frequency === frequency.value
                                }
                                onClick={() =>
                                    visit(frequency.value, period.date)
                                }
                                className={cn(
                                    'rounded-full px-3.5 py-1.5 text-sm font-semibold transition-colors',
                                    period.frequency === frequency.value
                                        ? 'bg-white text-ink shadow-landing-sm'
                                        : 'text-ink-500 hover:text-ink',
                                )}
                            >
                                {frequency.label}
                            </button>
                        ))}
                    </div>
                    <div className="flex items-center gap-1">
                        <button
                            type="button"
                            onClick={() =>
                                visit(period.frequency, period.previous)
                            }
                            className="rounded-full p-2 text-ink-500 hover:bg-surface-100 hover:text-ink"
                            aria-label="Previous period"
                        >
                            <ChevronLeft className="size-4" />
                        </button>
                        <span className="flex min-w-36 items-center justify-center gap-1.5 text-sm font-semibold text-ink">
                            <CalendarCheck className="size-4 text-highlight-dark" />
                            {period.label}
                        </span>
                        <button
                            type="button"
                            onClick={() => visit(period.frequency, period.next)}
                            className="rounded-full p-2 text-ink-500 hover:bg-surface-100 hover:text-ink"
                            aria-label="Next period"
                        >
                            <ChevronRight className="size-4" />
                        </button>
                    </div>
                    <Input
                        type="date"
                        value={period.date}
                        onChange={(event) =>
                            event.target.value &&
                            visit(period.frequency, event.target.value)
                        }
                        aria-label="Jump to date"
                        className="h-9 w-auto sm:ml-auto"
                    />
                </section>

                <section
                    aria-label="Period summary"
                    className="grid grid-cols-2 gap-3 lg:grid-cols-4"
                >
                    <SummaryCard
                        label="Due this period"
                        value={formatNaira(summary.expected)}
                        hint={`${summary.plans} ${summary.plans === 1 ? 'plan' : 'plans'}`}
                    />
                    <SummaryCard
                        label="Collected"
                        value={formatNaira(summary.collected)}
                        hint={`${collectedShare}% of what is due`}
                        tone="text-highlight-dark"
                    />
                    <SummaryCard
                        label="Outstanding"
                        value={formatNaira(summary.outstanding)}
                        hint={`${summary.pending + summary.partial} not fully paid`}
                        tone={
                            summary.outstanding > 0 ? 'text-red-700' : undefined
                        }
                    />
                    <SummaryCard
                        label="Fully paid"
                        value={`${summary.paid} / ${summary.plans}`}
                        hint={`${summary.partial} part paid · ${summary.pending} pending`}
                    />
                </section>

                <DataTable
                    title="Register"
                    description={`${period.label} · ${visibleRows.length} shown`}
                    columns={columns}
                    data={visibleRows}
                    getRowId={(row) => row.id}
                    searchable
                    searchPlaceholder="Search member, ADS-ID or plan"
                    searchText={(row) =>
                        `${row.member.name} ${row.member.memberId} ${row.name}`
                    }
                    defaultSort={{ key: 'status', direction: 'asc' }}
                    pageSize={25}
                    toolbar={
                        <div
                            role="tablist"
                            aria-label="Filter by status"
                            className="inline-flex gap-1 rounded-full bg-surface-100 p-1"
                        >
                            {(
                                [
                                    ['all', 'All', summary.plans],
                                    ['pending', 'Pending', summary.pending],
                                    ['partial', 'Part paid', summary.partial],
                                    ['paid', 'Paid', summary.paid],
                                ] as const
                            ).map(([key, label, count]) => (
                                <button
                                    key={key}
                                    type="button"
                                    role="tab"
                                    aria-selected={statusFilter === key}
                                    onClick={() => setStatusFilter(key)}
                                    className={cn(
                                        'rounded-full px-2.5 py-1 text-xs font-semibold transition-colors',
                                        statusFilter === key
                                            ? 'bg-white text-ink shadow-landing-sm'
                                            : 'text-ink-500 hover:text-ink',
                                    )}
                                >
                                    {label}{' '}
                                    <span className="text-ink-400">
                                        {count}
                                    </span>
                                </button>
                            ))}
                        </div>
                    }
                    empty={{
                        icon: CalendarCheck,
                        title: 'No contributions due',
                        description:
                            'No active plans with this frequency run during this period.',
                    }}
                />
            </MemberPage>
        </>
    );
}

function SummaryCard({
    label,
    value,
    hint,
    tone,
}: {
    label: string;
    value: string;
    hint: string;
    tone?: string;
}) {
    return (
        <section className="min-w-0 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={cn(
                    'mt-1 truncate font-display text-xl font-semibold text-ink tabular-nums',
                    tone,
                )}
            >
                {value}
            </p>
            <p className="truncate text-xs text-ink-500">{hint}</p>
        </section>
    );
}

Contributions.layout = {
    breadcrumbs: [{ title: 'Contributions', href: index() }],
};
