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

type Row = {
    location: string; total_leads: number; paid: number; org: number;
    scheduled_tours: number; booked_online: number; completed_tours: number; leases_signed: number;
};
type Totals = Row extends never ? never : Omit<Row, 'location'> & { conversion_rate: number };
type Source = { source: string; count: number; paid: boolean };
type Stage = { stage: string; count: number; percent: number };

export default function Pipeline() {
    const props = usePage().props as unknown as {
        rows: Row[]; totals: Totals; sources: Source[]; funnel: Stage[];
        period: { start: string; end: string }; location: string | null;
        locationOptions: { id: number; name: string }[];
    };
    const { rows, totals, sources, funnel, 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/pipeline', { 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 f = (d: Date) => d.toISOString().slice(0, 10);
        setStart(f(s)); setEnd(f(e));
        router.get('/portfolio/pipeline', { start: f(s), end: f(e), location: location ?? '' }, { preserveState: true });
    };

    const exportCsv = () => {
        const head = ['Location','Total Leads','Paid','Org','Scheduled Tours','Booked Online','Completed Tours','Leases Signed'];
        const body = rows.map(r => [r.location, r.total_leads, r.paid, r.org, r.scheduled_tours, r.booked_online, r.completed_tours, r.leases_signed]);
        const csv = [head, ...body].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 = `pipeline-${period.start}_${period.end}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Pipeline" />
            <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">
                        <Users2 className="size-5 text-primary" /> Pipeline
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">Salesforce leads through tours to signed leases.</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>

                {/* Funnel */}
                <div className="mb-5 grid gap-3 sm:grid-cols-4">
                    {funnel.map((s) => (
                        <div key={s.stage} className="rounded-xl border border-border bg-card p-4">
                            <p className="text-[11px] uppercase tracking-wide text-muted-foreground">{s.stage}</p>
                            <p className="mt-1 text-2xl font-semibold text-foreground">{s.count}</p>
                            <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-muted">
                                <div className="h-full rounded-full bg-primary" style={{ width: `${s.percent}%` }} />
                            </div>
                            <p className="mt-1 text-[11px] text-muted-foreground">{s.percent}% of leads</p>
                        </div>
                    ))}
                </div>

                {sources.length > 0 && (
                    <div className="mb-5 flex flex-wrap items-center gap-1.5">
                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Lead sources:</span>
                        {sources.map((s) => (
                            <span key={s.source}
                                className={`rounded-full border px-2.5 py-1 text-xs ${s.paid
                                    ? 'border-primary/30 bg-primary/10 text-primary'
                                    : 'border-border bg-card text-muted-foreground'}`}>
                                <span className="font-semibold">{s.count}</span> {s.source}
                            </span>
                        ))}
                    </div>
                )}

                <div className="overflow-x-auto rounded-xl border border-border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-xs uppercase tracking-wide text-muted-foreground">
                            <tr>
                                <th className="px-4 py-2.5 text-left font-medium">Location</th>
                                <th className="px-4 py-2.5 text-right font-medium">Total leads</th>
                                <th className="px-4 py-2.5 text-right font-medium">Paid</th>
                                <th className="px-4 py-2.5 text-right font-medium">Org</th>
                                <th className="px-4 py-2.5 text-right font-medium">Scheduled tours</th>
                                <th className="px-4 py-2.5 text-right font-medium">Booked online</th>
                                <th className="px-4 py-2.5 text-right font-medium">Completed tours</th>
                                <th className="px-4 py-2.5 text-right font-medium">Leases signed</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 font-medium text-foreground">{r.total_leads}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.paid}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.org}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.scheduled_tours}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.booked_online}</td>
                                    <td className="px-4 py-2.5 text-right text-muted-foreground">{r.completed_tours}</td>
                                    <td className="px-4 py-2.5 text-right font-medium text-emerald-600">{r.leases_signed}</td>
                                </tr>
                            ))}
                            {rows.length > 0 && (
                                <tr className="bg-muted/30 font-semibold">
                                    <td className="px-4 py-2.5 text-foreground">Total</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.total_leads}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.paid}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.org}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.scheduled_tours}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.booked_online}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{totals.completed_tours}</td>
                                    <td className="px-4 py-2.5 text-right text-emerald-600">{totals.leases_signed}</td>
                                </tr>
                            )}
                            {rows.length === 0 && (
                                <tr><td colSpan={8} className="px-4 py-12 text-center text-muted-foreground">
                                    No pipeline data. Sync Salesforce leads from Data Manager first.
                                </td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}
