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

type Tenant = {
    tenant: string; location: string; unit: string; email: string | null; phone: string | null;
    balance: number; move_in: string | null; lease_end: string | null;
    tenure_years: number | null; tenure_bucket: string;
    license_number: string | null; license_expiration: string | null; license_expired: boolean;
};

export default function Tenants() {
    const props = usePage().props as unknown as {
        tenants: Tenant[];
        buckets: { under_1: number; one_two: number; two_three: number; three_plus: number; total: number };
        location: string | null;
        locationOptions: { id: number; name: string }[];
    };
    const { tenants, buckets, location, locationOptions } = props;

    const [q, setQ] = useState('');
    const [delinquentOnly, setDelinquentOnly] = useState(false);
    const [expiredOnly, setExpiredOnly] = useState(false);

    const filtered = tenants.filter((t) => {
        if (delinquentOnly && t.balance <= 0) return false;
        if (expiredOnly && !t.license_expired) return false;
        if (!q) return true;
        const hay = `${t.tenant} ${t.email ?? ''} ${t.phone ?? ''} ${t.unit} ${t.location}`.toLowerCase();
        return hay.includes(q.toLowerCase());
    });

    const exportCsv = () => {
        const head = ['Tenant','Location','Unit','Email','Phone','Balance','Move In','Lease End','Tenure (yrs)'];
        const body = filtered.map(t => [t.tenant, t.location, t.unit, t.email ?? '', t.phone ?? '', t.balance, t.move_in ?? '', t.lease_end ?? '', t.tenure_years ?? '']);
        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 = `tenants-${new Date().toISOString().slice(0,10)}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Tenants" />
            <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">
                        <Users className="size-5 text-primary" /> Tenants
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Active tenants across your locations.</p>
                </header>

                <PortfolioTabs />

                <div className="mb-4 flex flex-wrap items-center gap-2">
                    <div className="relative">
                        <Search className="pointer-events-none absolute left-2.5 top-2 size-4 text-muted-foreground" />
                        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="name, email, phone, unit…"
                            className="w-64 rounded-md border border-border bg-background py-1.5 pl-8 pr-3 text-sm" />
                    </div>
                    <LocationFilter options={locationOptions} value={location}
                        onChange={(v) => router.get('/portfolio/tenants', { location: v }, { preserveState: true })} />
                    <label className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <input type="checkbox" checked={delinquentOnly} onChange={(e) => setDelinquentOnly(e.target.checked)} />
                        Delinquent only
                    </label>
                    <label className="flex items-center gap-1.5 text-sm text-muted-foreground">
                        <input type="checkbox" checked={expiredOnly} onChange={(e) => setExpiredOnly(e.target.checked)} />
                        Expired License
                    </label>
                    <span className="ml-auto text-sm text-muted-foreground">{filtered.length} records</span>
                    <button onClick={exportCsv} disabled={filtered.length === 0}
                        className="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-5">
                    <Bucket label="< 1 yr" value={buckets.under_1} tone="rose" />
                    <Bucket label="1-2 yr" value={buckets.one_two} tone="amber" />
                    <Bucket label="2-3 yr" value={buckets.two_three} tone="yellow" />
                    <Bucket label="3+ yr" value={buckets.three_plus} tone="emerald" />
                    <Bucket label="Total" value={buckets.total} />
                </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">Tenant</th>
                                <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">Contact</th>
                                <th className="px-4 py-2.5 text-right font-medium">Balance</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">Tenure</th>
                                <th className="px-4 py-2.5 font-medium">Mini License Exp</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {filtered.map((t, i) => (
                                <tr key={i} className={t.balance > 0 ? 'bg-destructive/5' : ''}>
                                    <td className="px-4 py-2.5 font-medium text-foreground">{t.tenant}</td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{t.location}</td>
                                    <td className="px-4 py-2.5 text-foreground">{t.unit}</td>
                                    <td className="px-4 py-2.5 text-xs text-muted-foreground">
                                        {t.email && <span className="block">{t.email}</span>}
                                        {t.phone && <span className="block">{t.phone}</span>}
                                    </td>
                                    <td className={`px-4 py-2.5 text-right ${t.balance > 0 ? 'font-medium text-destructive' : 'text-muted-foreground'}`}>
                                        {t.balance ? money(t.balance) : '—'}
                                    </td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{t.move_in ?? '—'}</td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{t.lease_end ?? '—'}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{t.tenure_years ?? '—'}</td>
                                    <td className={`px-4 py-2.5 text-xs ${t.license_expired ? 'font-medium text-destructive' : 'text-muted-foreground'}`}>
                                        {t.license_expiration ?? '—'}{t.license_expired && ' (expired)'}
                                        {t.license_number && <span className="ml-1 opacity-60">#{t.license_number}</span>}
                                    </td>
                                </tr>
                            ))}
                            {filtered.length === 0 && (
                                <tr><td colSpan={9} className="px-4 py-12 text-center text-muted-foreground">No tenants match.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

function Bucket({ label, value, tone }: { label: string; value: number; 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-2xl font-semibold">{value}</p>
            <p className="mt-0.5 text-[11px] uppercase tracking-wide opacity-80">{label}</p>
        </div>
    );
}
