import { Head, router } from '@inertiajs/react';
import { ChevronDown } from 'lucide-react';
import AccountingNav from '@/components/accounting-nav';
import type { ReportKey } from '@/components/accounting-nav';
import { Label } from '@/components/ui/label';
import MemberPage from '@/components/member/member-page';
import { formatDate, formatNaira } from '@/lib/format';
import { trialBalance } from '@/routes/admin/accounting';
import type { SelectOption } from '@/types';

export type LedgerEntry = {
    date: string;
    description: string;
    reference: string;
    debit: number;
    credit: number;
    balance: number;
};

export type LedgerProps = {
    account: { value: string; label: string; type: string };
    accounts: SelectOption[];
    from: string;
    to: string;
    opening: number;
    pageOpening: number;
    closing: number;
    pagination: { page: number; lastPage: number; count: number };
    entries: LedgerEntry[];
    totals: { debit: number; credit: number };
};

export function LedgerTable({
    props,
    debitLabel = 'Debit',
    creditLabel = 'Credit',
}: {
    props: LedgerProps;
    debitLabel?: string;
    creditLabel?: string;
}) {
    return (
        <section className="overflow-x-auto rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm">
            <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-3 font-semibold">Date</th>
                        <th className="px-4 py-3 font-semibold">Details</th>
                        <th className="px-4 py-3 text-right font-semibold">
                            {debitLabel}
                        </th>
                        <th className="px-4 py-3 text-right font-semibold">
                            {creditLabel}
                        </th>
                        <th className="px-4 py-3 text-right font-semibold">
                            Balance
                        </th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-surface-100 tabular-nums">
                    <tr className="bg-surface-50 font-semibold text-ink-700">
                        <td className="px-4 py-2 whitespace-nowrap">
                            {formatDate(props.from)}
                        </td>
                        <td className="px-4 py-2" colSpan={3}>
                            {props.pagination.page > 1
                                ? 'Brought forward'
                                : 'Opening balance'}
                        </td>
                        <td className="px-4 py-2 text-right">
                            {formatNaira(
                                props.pagination.page > 1
                                    ? props.pageOpening
                                    : props.opening,
                            )}
                        </td>
                    </tr>
                    {props.entries.map((entry, position) => (
                        <tr key={`${entry.reference}-${position}`}>
                            <td className="px-4 py-2 whitespace-nowrap text-ink-500">
                                {formatDate(entry.date)}
                            </td>
                            <td className="px-4 py-2">
                                <span className="block text-ink">
                                    {entry.description}
                                </span>
                                <span className="block font-mono text-xs text-ink-400">
                                    {entry.reference}
                                </span>
                            </td>
                            <td className="px-4 py-2 text-right">
                                {entry.debit ? formatNaira(entry.debit) : ''}
                            </td>
                            <td className="px-4 py-2 text-right">
                                {entry.credit ? formatNaira(entry.credit) : ''}
                            </td>
                            <td className="px-4 py-2 text-right text-ink-700">
                                {formatNaira(entry.balance)}
                            </td>
                        </tr>
                    ))}
                </tbody>
                <tfoot>
                    <tr className="border-t-2 border-surface-200 font-semibold text-ink tabular-nums">
                        <td className="px-4 py-3" colSpan={2}>
                            Closing balance · {formatDate(props.to)}
                        </td>
                        <td className="px-4 py-3 text-right">
                            {formatNaira(props.totals.debit)}
                        </td>
                        <td className="px-4 py-3 text-right">
                            {formatNaira(props.totals.credit)}
                        </td>
                        <td className="px-4 py-3 text-right">
                            {formatNaira(props.closing)}
                        </td>
                    </tr>
                </tfoot>
            </table>
            {props.pagination.lastPage > 1 && (
                <nav className="flex items-center justify-between gap-3 border-t border-surface-100 px-4 py-3 text-sm print:hidden">
                    <span className="text-ink-500">
                        Page {props.pagination.page} of{' '}
                        {props.pagination.lastPage} · {props.pagination.count}{' '}
                        entries
                    </span>
                    <span className="flex gap-2">
                        {[
                            ['Previous', props.pagination.page - 1],
                            ['Next', props.pagination.page + 1],
                        ].map(([label, target]) => (
                            <button
                                key={label}
                                type="button"
                                disabled={
                                    Number(target) < 1 ||
                                    Number(target) > props.pagination.lastPage
                                }
                                onClick={() => {
                                    const query = new URLSearchParams(
                                        window.location.search,
                                    );
                                    query.set('page', String(target));
                                    router.get(
                                        `${window.location.pathname}?${query}`,
                                        {},
                                        { preserveScroll: true },
                                    );
                                }}
                                className="rounded-md border border-input px-3 py-1 font-semibold text-ink-700 hover:bg-surface-50 disabled:opacity-40"
                            >
                                {label}
                            </button>
                        ))}
                    </span>
                </nav>
            )}
        </section>
    );
}

export default function GeneralLedger(props: LedgerProps) {
    const current: ReportKey = 'general-ledger';

    const chooseAccount = (value: string) => {
        const query = new URLSearchParams(window.location.search);
        query.set('account', value);
        router.get(
            `${window.location.pathname}?${query}`,
            {},
            { preserveScroll: true, replace: true },
        );
    };

    return (
        <>
            <Head title={`General ledger · ${props.account.label}`} />

            <MemberPage
                title="General ledger"
                description={`${props.account.value} · ${props.account.label}`}
            >
                <AccountingNav
                    current={current}
                    dates={{ from: props.from, to: props.to }}
                    extra={
                        <div className="grid gap-1">
                            <Label htmlFor="account">Account</Label>
                            <div className="relative">
                                <select
                                    id="account"
                                    value={props.account.value}
                                    onChange={(event) =>
                                        chooseAccount(event.target.value)
                                    }
                                    className="h-9 appearance-none rounded-md border border-input bg-white pr-8 pl-3 text-sm text-ink shadow-xs"
                                >
                                    {props.accounts.map((account) => (
                                        <option
                                            key={account.value}
                                            value={account.value}
                                        >
                                            {account.label}
                                        </option>
                                    ))}
                                </select>
                                <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 size-4 -translate-y-1/2 text-ink-400" />
                            </div>
                        </div>
                    }
                />

                <LedgerTable props={props} />
            </MemberPage>
        </>
    );
}

GeneralLedger.layout = {
    breadcrumbs: [{ title: 'Accounting', href: trialBalance() }],
};
