import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { PortfolioTabs, LocationFilter, money } from '@/components/portfolio/PortfolioTabs';
import { DollarSign, Download } from 'lucide-react';

type Row = { location: string; income: number; transactions: number };
type Cat = { category: string; income: number; transactions: number };

export default function Income() {
    const props = usePage().props as unknown as {
        rows: Row[]; total: number; transactionCount: number; categories: Cat[];
        period: { start: string; end: string }; location: string | null;
        locationOptions: { id: number; name: string }[];
    };
    const { rows, total, transactionCount, categories, period, location, locationOptions } = props;

    const [start, setStart] = useState(period.start);
    const [end, setEnd] = useState(period.end);

    const apply = (extra: Record<string, string> = {}) =>
        router.get('/portfolio/income', { start, end, location: location ?? '', ...extra }, { preserveState: true });

    const quick = (days: number) => {
        const e = new Date(); const s = new Date(); s.setDate(s.getDate() - days);
        const fmtD = (d: Date) => d.toISOString().slice(0, 10);
        setStart(fmtD(s)); setEnd(fmtD(e));
        router.get('/portfolio/income', { start: fmtD(s), end: fmtD(e), location: location ?? '' }, { preserveState: true });
    };

    const exportCsv = () => {
        const csv = [['Location','Income','Transactions'], ...rows.map(r => [r.location, r.income, r.transactions])]
            .map(r => r.map(c => `"${String(c)}"`).join(',')).join('\n');
        const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
        const a = document.createElement('a'); a.href = url; a.download = `income-${period.start}_${period.end}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Income" />
            <div className="mx-auto w-full max-w-5xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <DollarSign className="size-5 text-primary" /> Income
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Money received, from the Rentec bank ledger.</p>
                </header>

                <PortfolioTabs />

                <div className="mb-4 flex flex-wrap items-end gap-2">
                    <div>
                        <label className="mb-1 block text-[11px] text-muted-foreground">From</label>
                        <input type="date" value={start} onChange={(e) => setStart(e.target.value)}
                            className="rounded-md border border-border bg-background px-2.5 py-1.5 text-sm" />
                    </div>
                    <div>
                        <label className="mb-1 block text-[11px] text-muted-foreground">To</label>
                        <input type="date" value={end} onChange={(e) => setEnd(e.target.value)}
                            className="rounded-md border border-border bg-background px-2.5 py-1.5 text-sm" />
                    </div>
                    <button onClick={() => apply()} className="rounded-md bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground hover:opacity-90">
                        Apply
                    </button>
                    <div className="flex gap-1">
                        {[7, 30, 90].map((d) => (
                            <button key={d} onClick={() => quick(d)}
                                className="rounded-md border border-border px-2.5 py-1.5 text-xs hover:bg-muted">{d}d</button>
                        ))}
                    </div>
                    <LocationFilter options={locationOptions} value={location} onChange={(v) => apply({ location: v })} />
                    <button onClick={exportCsv} disabled={rows.length === 0}
                        className="ml-auto inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm font-medium hover:bg-muted disabled:opacity-50">
                        <Download className="size-3.5" /> Export CSV
                    </button>
                </div>

                <div className="mb-5 grid gap-3 sm:grid-cols-3">
                    <Card label="Total received" value={money(total)} big />
                    <Card label="Transactions" value={transactionCount.toLocaleString()} />
                    <Card label="Period" value={`${period.start} → ${period.end}`} small />
                </div>

                <div className="mb-6 overflow-hidden rounded-xl border border-border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-left text-xs uppercase tracking-wide text-muted-foreground">
                            <tr>
                                <th className="px-4 py-2.5 font-medium">Location</th>
                                <th className="px-4 py-2.5 text-right font-medium">Transactions</th>
                                <th className="px-4 py-2.5 text-right font-medium">Income</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {rows.map((r) => (
                                <tr key={r.location}>
                                    <td className="px-4 py-2.5 text-foreground">{r.location}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.transactions}</td>
                                    <td className="px-4 py-2.5 text-right font-medium text-foreground">{money(r.income)}</td>
                                </tr>
                            ))}
                            {rows.length > 0 && (
                                <tr className="bg-muted/30">
                                    <td className="px-4 py-2.5 font-semibold text-foreground">Total</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{transactionCount}</td>
                                    <td className="px-4 py-2.5 text-right font-semibold text-foreground">{money(total)}</td>
                                </tr>
                            )}
                            {rows.length === 0 && (
                                <tr><td colSpan={3} className="px-4 py-12 text-center text-muted-foreground">
                                    No income in this period. If transactions haven't been synced yet, run a Rentec sync including the transactions resource.
                                </td></tr>
                            )}
                        </tbody>
                    </table>
                </div>

                {categories.length > 0 && (
                    <section>
                        <h2 className="mb-3 text-sm font-medium text-muted-foreground">By category</h2>
                        <div className="grid gap-2 sm:grid-cols-2">
                            {categories.map((c) => (
                                <div key={c.category} className="flex items-center justify-between rounded-lg border border-border bg-card px-4 py-2.5">
                                    <span className="text-sm text-foreground">{c.category}</span>
                                    <span className="text-sm font-medium text-foreground">{money(c.income)}</span>
                                </div>
                            ))}
                        </div>
                    </section>
                )}
            </div>
        </>
    );
}

function Card({ label, value, big, small }: { label: string; value: string; big?: boolean; small?: boolean }) {
    return (
        <div className="rounded-xl border border-border bg-card p-4">
            <p className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</p>
            <p className={`mt-1 font-semibold text-foreground ${big ? 'text-2xl' : small ? 'text-xs' : 'text-xl'}`}>{value}</p>
        </div>
    );
}
