import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Printer } from 'lucide-react';
import type { FormEvent } from 'react';
import { useState } from 'react';
import { LandingLogoMark } from '@/components/landing/landing-logo';
import MemberPage from '@/components/member/member-page';
import OrganisationContact from '@/components/organisation-contact';
import { Button } from '@/components/ui/button';
import { formatDate, formatDateTime, formatNaira } from '@/lib/format';
import { show, statement } from '@/routes/wallet';
import type { Organisation, TransactionItem, WalletSummary } from '@/types';

type Props = {
    organisation: Organisation;
    wallet: WalletSummary & { memberId: string };
    statementUrl: string;
    backUrl: string;
    period: { from: string; to: string };
    openingBalance: number;
    closingBalance: number;
    totalIn: number;
    totalOut: number;
    entries: TransactionItem[];
    generatedAt: string;
};

const fieldClasses =
    'h-10 rounded-md border border-input bg-white px-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15';

export default function Statement({
    organisation,
    wallet,
    statementUrl,
    backUrl,
    period,
    openingBalance,
    closingBalance,
    totalIn,
    totalOut,
    entries,
    generatedAt,
}: Props) {
    const [from, setFrom] = useState(period.from);
    const [to, setTo] = useState(period.to);

    const changePeriod = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        router.get(statementUrl, { from, to });
    };

    return (
        <>
            <Head title="Account statement" />

            <MemberPage
                title="Account statement"
                description="Settled transactions for the selected period."
                actions={
                    <div className="print-hidden flex gap-2">
                        <Link
                            href={backUrl}
                            className="inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold text-ink-500 hover:text-brand"
                        >
                            <ArrowLeft className="size-4" />
                            Back
                        </Link>
                        <button
                            type="button"
                            onClick={() => window.print()}
                            className="inline-flex items-center gap-2 rounded-full bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-hover"
                        >
                            <Printer className="size-4" />
                            Print / save PDF
                        </button>
                    </div>
                }
            >
                <form
                    onSubmit={changePeriod}
                    className="print-hidden flex flex-wrap items-end gap-3 rounded-landing-lg border border-surface-200 bg-white p-4"
                    aria-label="Statement period"
                >
                    <label className="grid gap-1.5 text-xs font-semibold text-ink-500">
                        From
                        <input
                            type="date"
                            value={from}
                            max={to}
                            onChange={(event) => setFrom(event.target.value)}
                            className={fieldClasses}
                        />
                    </label>
                    <label className="grid gap-1.5 text-xs font-semibold text-ink-500">
                        To
                        <input
                            type="date"
                            value={to}
                            min={from}
                            onChange={(event) => setTo(event.target.value)}
                            className={fieldClasses}
                        />
                    </label>
                    <Button type="submit" className="h-10">
                        Update
                    </Button>
                </form>

                <article className="rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-8">
                    <header className="flex flex-wrap items-start justify-between gap-4 border-b border-surface-200 pb-5">
                        <div className="flex items-center gap-3">
                            <LandingLogoMark />
                            <div>
                                <p className="font-display text-lg font-semibold text-ink">
                                    {organisation.name}
                                </p>
                                <OrganisationContact
                                    organisation={organisation}
                                />
                                <p className="text-xs text-ink-400">
                                    Member statement
                                </p>
                            </div>
                        </div>
                        <dl className="grid gap-1 text-right text-xs text-ink-500">
                            <div>
                                <dt className="inline">Account name: </dt>
                                <dd className="inline font-semibold text-ink">
                                    {wallet.accountName}
                                </dd>
                            </div>
                            <div>
                                <dt className="inline">Member ID: </dt>
                                <dd className="inline font-semibold text-ink">
                                    {wallet.memberId}
                                </dd>
                            </div>
                            <div>
                                <dt className="inline">Account number: </dt>
                                <dd className="inline font-semibold text-ink">
                                    {wallet.accountNumber}
                                </dd>
                            </div>
                            <div>
                                <dt className="inline">Period: </dt>
                                <dd className="inline font-semibold text-ink">
                                    {formatDate(period.from)} –{' '}
                                    {formatDate(period.to)}
                                </dd>
                            </div>
                        </dl>
                    </header>

                    <dl className="grid grid-cols-2 gap-4 border-b border-surface-200 py-5 text-sm lg:grid-cols-4">
                        {[
                            ['Opening balance', openingBalance],
                            ['Money in', totalIn],
                            ['Money out', totalOut],
                            ['Closing balance', closingBalance],
                        ].map(([term, amount]) => (
                            <div key={term}>
                                <dt className="text-xs text-ink-400">{term}</dt>
                                <dd className="mt-1 font-semibold text-ink tabular-nums">
                                    {formatNaira(amount as number)}
                                </dd>
                            </div>
                        ))}
                    </dl>

                    <div className="overflow-x-auto">
                        <table className="mt-4 w-full min-w-[640px] text-left text-sm">
                            <thead>
                                <tr className="text-xs text-ink-400">
                                    <th className="py-2 pr-3 font-semibold">
                                        Date
                                    </th>
                                    <th className="py-2 pr-3 font-semibold">
                                        Description
                                    </th>
                                    <th className="py-2 pr-3 font-semibold">
                                        Reference
                                    </th>
                                    <th className="py-2 pr-3 text-right font-semibold">
                                        Debit
                                    </th>
                                    <th className="py-2 pr-3 text-right font-semibold">
                                        Credit
                                    </th>
                                    <th className="py-2 text-right font-semibold">
                                        Balance
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-surface-100">
                                <tr className="bg-surface-50/60">
                                    <td className="py-2.5 pr-3 whitespace-nowrap text-ink-500">
                                        {formatDate(period.from)}
                                    </td>
                                    <td
                                        colSpan={4}
                                        className="py-2.5 pr-3 font-semibold text-ink"
                                    >
                                        Opening balance
                                    </td>
                                    <td className="py-2.5 text-right font-semibold text-ink tabular-nums">
                                        {formatNaira(openingBalance)}
                                    </td>
                                </tr>
                                {entries.length === 0 ? (
                                    <tr>
                                        <td
                                            colSpan={6}
                                            className="py-8 text-center text-ink-400"
                                        >
                                            No settled transactions in this
                                            period.
                                        </td>
                                    </tr>
                                ) : (
                                    entries.map((entry) => (
                                        <tr key={entry.id}>
                                            <td className="py-2.5 pr-3 whitespace-nowrap text-ink-500">
                                                {formatDateTime(
                                                    entry.createdAt,
                                                )}
                                            </td>
                                            <td className="py-2.5 pr-3 text-ink">
                                                {entry.description}
                                            </td>
                                            <td className="py-2.5 pr-3 font-mono text-xs text-ink-400">
                                                {entry.reference}
                                            </td>
                                            <td className="py-2.5 pr-3 text-right text-ink tabular-nums">
                                                {entry.direction === 'debit'
                                                    ? formatNaira(entry.amount)
                                                    : ''}
                                            </td>
                                            <td className="py-2.5 pr-3 text-right text-highlight-dark tabular-nums">
                                                {entry.direction === 'credit'
                                                    ? formatNaira(entry.amount)
                                                    : ''}
                                            </td>
                                            <td className="py-2.5 text-right font-medium text-ink tabular-nums">
                                                {entry.balanceAfter === null
                                                    ? '—'
                                                    : formatNaira(
                                                          entry.balanceAfter,
                                                      )}
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>

                    <p className="mt-6 text-xs text-ink-400">
                        Generated {formatDateTime(generatedAt)}. Pending and
                        failed transactions are not included.
                    </p>
                </article>
            </MemberPage>
        </>
    );
}

Statement.layout = {
    breadcrumbs: [
        { title: 'Wallet', href: show() },
        { title: 'Statement', href: statement() },
    ],
};
