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

type Row = {
    lease_id: number | null; location: string; unit: string; tenant: string;
    balance: number; tenure_years: number | null; move_in: string | null;
    lease_begin: string | null; lease_end: string; days_left: number; recurring_rent: number;
};

/** Urgency banding — mirrors how the ops team scans the list. */
function rowTone(days: number) {
    if (days <= 30) return 'bg-destructive/5';
    if (days <= 60) return 'bg-amber-500/5';
    return '';
}

export default function Retention() {
    const props = usePage().props as unknown as {
        rows: Row[];
        summary: { first: number; second: number; third: number; long_term: number; total: number; outstanding_balance: number; monthly_rent: number };
        location: string | null; window: number;
        locationOptions: { id: number; name: string }[];
    };
    const { rows, summary, location, window: win, locationOptions } = props;

    const go = (params: Record<string, string | number>) =>
        router.get('/portfolio/retention', { location: location ?? '', window: win, ...params }, { preserveState: true });

    const exportCsv = () => {
        const head = ['Location','Unit','Tenant','Balance','Tenure (yrs)','Move In','Lease Begin','Lease End','Days Left','Monthly Rent'];
        const body = rows.map(r => [r.location, r.unit, r.tenant, r.balance, r.tenure_years ?? '', r.move_in ?? '', r.lease_begin ?? '', r.lease_end, r.days_left, r.recurring_rent]);
        const csv = [head, ...body].map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
        const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
        const a = document.createElement('a'); a.href = url; a.download = `retention-${new Date().toISOString().slice(0,10)}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Retention" />
            <div className="mx-auto w-full max-w-7xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <CalendarClock className="size-5 text-primary" /> Retention
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Leases ending within the selected window.</p>
                </header>

                <PortfolioTabs />

                <div className="mb-4 flex flex-wrap items-center gap-2">
                    <LocationFilter options={locationOptions} value={location} onChange={(v) => go({ location: v })} />
                    <select value={win} onChange={(e) => go({ window: e.target.value })}
                        className="rounded-md border border-border bg-background px-3 py-1.5 text-sm">
                        <option value={30}>Next 30 days</option>
                        <option value={60}>Next 60 days</option>
                        <option value={90}>Next 90 days</option>
                        <option value={180}>Next 180 days</option>
                    </select>
                    <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 lg:grid-cols-6">
                    <Chip label="1st renewal" value={summary.first} tone="rose" />
                    <Chip label="2nd renewal" value={summary.second} tone="amber" />
                    <Chip label="3rd renewal" value={summary.third} tone="yellow" />
                    <Chip label="Long term" value={summary.long_term} tone="emerald" />
                    <Chip label="Total leases" value={summary.total} />
                    <Chip label="Outstanding" value={money(summary.outstanding_balance)} />
                </div>

                <div className="overflow-x-auto 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 font-medium">Unit</th>
                                <th className="px-4 py-2.5 font-medium">Tenant</th>
                                <th className="px-4 py-2.5 text-right font-medium">Balance</th>
                                <th className="px-4 py-2.5 text-right font-medium">Tenure</th>
                                <th className="px-4 py-2.5 font-medium">Move In</th>
                                <th className="px-4 py-2.5 font-medium">Lease End</th>
                                <th className="px-4 py-2.5 text-right font-medium">Days Left</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {rows.map((r, i) => (
                                <tr key={r.lease_id ?? i} className={rowTone(r.days_left)}>
                                    <td className="px-4 py-2.5 text-foreground">{r.location}</td>
                                    <td className="px-4 py-2.5 text-foreground">{r.unit}</td>
                                    <td className="px-4 py-2.5 font-medium text-foreground">{r.tenant}</td>
                                    <td className={`px-4 py-2.5 text-right ${r.balance > 0 ? 'font-medium text-destructive' : 'text-muted-foreground'}`}>
                                        {r.balance ? money(r.balance) : '—'}
                                    </td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.tenure_years ?? '—'}</td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{r.move_in ?? '—'}</td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{r.lease_end}</td>
                                    <td className="px-4 py-2.5 text-right font-medium text-foreground">{r.days_left}</td>
                                </tr>
                            ))}
                            {rows.length === 0 && (
                                <tr><td colSpan={8} className="px-4 py-12 text-center text-muted-foreground">No leases expiring in this window.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

function Chip({ label, value, tone }: { label: string; value: number | string; tone?: string }) {
    const tones: Record<string, string> = {
        rose: 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-300',
        amber: 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300',
        yellow: 'border-yellow-200 bg-yellow-50 text-yellow-700 dark:border-yellow-500/30 dark:bg-yellow-500/10 dark:text-yellow-300',
        emerald: 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-300',
    };
    return (
        <div className={`rounded-xl border p-3 text-center ${tone ? tones[tone] : 'border-border bg-card'}`}>
            <p className="text-xl font-semibold">{value}</p>
            <p className="mt-0.5 text-[11px] uppercase tracking-wide opacity-80">{label}</p>
        </div>
    );
}
