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

type Vacancy = { location: string; unit: string; monthly_rent: number };

export default function Vacancies() {
    const props = usePage().props as unknown as {
        vacancies: Vacancy[]; location: string | null;
        locationOptions: { id: number; name: string }[];
    };
    const { vacancies, location, locationOptions } = props;

    const byLocation = vacancies.reduce<Record<string, number>>((acc, v) => {
        acc[v.location] = (acc[v.location] ?? 0) + 1; return acc;
    }, {});
    const potential = vacancies.reduce((sum, v) => sum + (v.monthly_rent || 0), 0);

    const exportCsv = () => {
        const csv = [['Location','Unit','Monthly Rent'], ...vacancies.map(v => [v.location, v.unit, v.monthly_rent])]
            .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 = `vacancies-${new Date().toISOString().slice(0,10)}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Vacancies" />
            <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">
                        <DoorOpen className="size-5 text-primary" /> Vacancies
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Suites without an active lease.</p>
                </header>

                <PortfolioTabs />

                <div className="mb-4 flex flex-wrap items-center gap-2">
                    <LocationFilter options={locationOptions} value={location}
                        onChange={(v) => router.get('/portfolio/vacancies', { location: v }, { preserveState: true })} />
                    <span className="ml-auto text-sm text-muted-foreground">
                        {vacancies.length} vacant · {money(potential)}/mo potential
                    </span>
                    <button onClick={exportCsv} disabled={vacancies.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>

                {Object.keys(byLocation).length > 0 && (
                    <div className="mb-5 flex flex-wrap gap-2">
                        {Object.entries(byLocation).sort().map(([loc, n]) => (
                            <span key={loc} className="rounded-full border border-border bg-card px-3 py-1 text-xs">
                                {loc} <span className="ml-1 font-semibold text-foreground">{n}</span>
                            </span>
                        ))}
                    </div>
                )}

                <div className="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 font-medium">Unit</th>
                                <th className="px-4 py-2.5 text-right font-medium">Asking Rent</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {vacancies.map((v, i) => (
                                <tr key={i}>
                                    <td className="px-4 py-2.5 text-muted-foreground">{v.location}</td>
                                    <td className="px-4 py-2.5 font-medium text-foreground">{v.unit}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{v.monthly_rent ? money(v.monthly_rent) : '—'}</td>
                                </tr>
                            ))}
                            {vacancies.length === 0 && (
                                <tr><td colSpan={3} className="px-4 py-12 text-center text-muted-foreground">No vacancies — everything's leased.</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}
