import { Head, Link, router, usePage } from '@inertiajs/react';
import { PortfolioTabs, LocationFilter, money } from '@/components/portfolio/PortfolioTabs';
import { CalendarClock, Download, ArrowRight } 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;
    license_number: string | null; license_expiration: string | null; license_expired: boolean;
};
type Summary = {
    counts: Record<string, number>;
    projected: Record<string, number>;
    total_leases: number;
    non_renewal_projected: number;
    broken_projected: number;
    scheduled_move_outs: number;
    grand_total_projected_mo: number;
    outstanding_balance: number;
};

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: Summary; 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">
                        Expiring leases, renewal buckets, and projected move-outs.
                    </p>
                </header>

                <PortfolioTabs />

                {/* Grand total banner */}
                <div className="mb-4 rounded-xl bg-primary px-6 py-4 text-center text-primary-foreground">
                    <span className="text-3xl font-semibold">{summary.grand_total_projected_mo}</span>
                    <span className="ml-3 text-sm uppercase tracking-wide opacity-90">Grand total projected MO</span>
                </div>

                {/* Renewal tiles: count on top, projected MO underneath */}
                <div className="mb-4 grid gap-2 sm:grid-cols-4 lg:grid-cols-7">
                    <Tile label="1st renewal" count={summary.counts.first} proj={summary.projected.first} tone="rose" />
                    <Tile label="2nd renewal" count={summary.counts.second} proj={summary.projected.second} tone="amber" />
                    <Tile label="3rd renewal" count={summary.counts.third} proj={summary.projected.third} tone="yellow" />
                    <Tile label="Long term" count={summary.counts.long_term} proj={summary.projected.long_term} tone="emerald" />
                    <Tile label="Total" count={summary.total_leases} proj={summary.non_renewal_projected} projLabel="Non renewal proj" />
                    <Tile label="Broken projection" proj={summary.broken_projected} tone="slate" />
                    <Tile label="Scheduled MO" count={summary.scheduled_move_outs} tone="dark" />
                </div>

                <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>
                        <option value={365}>Next 12 months</option>
                    </select>
                    <Link href={`/portfolio/monthly-projections?location=${location ?? ''}&window=${win}`}
                        className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground hover:opacity-90">
                        Monthly Projections <ArrowRight className="size-3.5" />
                    </Link>
                    <span className="text-sm text-muted-foreground">{rows.length} leases</span>
                    <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="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 (yrs)</th>
                                <th className="px-4 py-2.5 font-medium">Move In</th>
                                <th className="px-4 py-2.5 font-medium">Lease Begin</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>
                                <th className="px-4 py-2.5 font-medium">Mini License Exp</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 ? '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_begin ?? '—'}</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>
                                    <td className={`px-4 py-2.5 text-xs ${r.license_expired ? 'font-medium text-destructive' : 'text-muted-foreground'}`}>
                                        {r.license_expiration ?? '—'}{r.license_expired && ' (expired)'}
                                        {r.license_number && <span className="ml-1 opacity-60">#{r.license_number}</span>}
                                    </td>
                                </tr>
                            ))}
                            {rows.length === 0 && (
                                <tr><td colSpan={10} className="px-4 py-12 text-center text-muted-foreground">No leases expiring in this window.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

function Tile({ label, count, proj, projLabel, tone }: {
    label: string; count?: number; proj?: number; projLabel?: 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',
        slate: 'border-slate-300 bg-slate-100 text-slate-700 dark:border-slate-500/30 dark:bg-slate-500/10 dark:text-slate-300',
        dark: 'border-slate-800 bg-slate-800 text-white',
    };
    return (
        <div className={`rounded-xl border p-3 text-center ${tone ? tones[tone] : 'border-border bg-card'}`}>
            {count !== undefined && <p className="text-xl font-semibold">{count}</p>}
            <p className="text-[10px] uppercase tracking-wide opacity-80">{label}</p>
            {proj !== undefined && (
                <>
                    <p className="mt-1.5 border-t border-current/20 pt-1.5 text-lg font-semibold">{proj}</p>
                    <p className="text-[9px] uppercase tracking-wide opacity-70">{projLabel ?? 'Projected MO'}</p>
                </>
            )}
        </div>
    );
}
