import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Search, Download, Target, RefreshCw } from 'lucide-react';

type Row = {
    id: number; status: string; match_type: string; match_detail: string | null;
    license_number: string | null; owner: string | null; business: string | null;
    profession: string | null; address: string | null; city_state_zip: string;
    zip: string | null; phone: string | null; expiration: string | null;
    expired: boolean; distance: number | null; county: string | null;
    competition: string | null; suites_at_address: number | null;
};
type Stats = {
    total: number; our_tenants: number; other_corp_tenants: number;
    in_salesforce: number; untouched: number; center_zip: string | null; county: string | null;
};

export default function Prospecting() {
    const props = usePage().props as unknown as {
        rows: Row[]; stats: Stats; mode: string;
        center: { name: string; zip: string | null; county: string | null } | null;
        professions: Record<string, string>; radii: number[];
        filters: Record<string, any>;
        locationOptions: { id: number; name: string }[];
    };
    const { rows, stats, mode, center, professions, radii, filters, locationOptions } = props;
    const [q, setQ] = useState(filters.q ?? '');

    const go = (patch: Record<string, any>) =>
        router.get('/prospecting', { ...filters, ...patch }, { preserveState: true });

    const exportCsv = () => {
        const head = ['Status','JC Location','License #','Owner','Business','Profession','Address','City/State/Zip','Phone','Distance (mi)','Expiration'];
        const body = rows.map(r => [r.status, r.match_detail ?? '', r.license_number ?? '', r.owner ?? '', r.business ?? '',
            r.profession ?? '', r.address ?? '', r.city_state_zip, r.phone ?? '', r.distance ?? '', r.expiration ?? '']);
        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 = `prospects-${filters.profession}-${new Date().toISOString().slice(0,10)}.csv`; a.click();
        URL.revokeObjectURL(url);
    };

    return (
        <>
            <Head title="Lead Prospecting" />
            <div className="mx-auto w-full max-w-[1600px] px-6 py-8">
                <header className="mb-5 flex items-start justify-between">
                    <div>
                        <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                            <Target className="size-5 text-primary" /> Lead Prospecting
                        </h1>
                        <p className="mt-1 text-sm text-muted-foreground">
                            Licensed professionals near your locations, cross-referenced against tenants and Salesforce.
                        </p>
                    </div>
                    <button onClick={() => router.post('/prospecting/rematch', {}, { preserveScroll: true })}
                        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">
                        <RefreshCw className="size-3.5" /> Rebuild matches
                    </button>
                </header>

                <div className="mb-5 flex flex-wrap gap-1">
                    {Object.entries(professions).map(([key, label]) => (
                        <button key={key} onClick={() => go({ profession: key })}
                            className={`border-b-2 px-3 py-2 text-sm font-medium transition ${
                                filters.profession === key
                                    ? 'border-primary text-primary'
                                    : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
                            {label}
                        </button>
                    ))}
                </div>

                <div className="mb-5 flex flex-wrap items-end gap-2 rounded-xl border border-border bg-card p-4">
                    <div>
                        <label className="mb-1 block text-[11px] text-muted-foreground">Location</label>
                        <select value={filters.location_id ?? ''} onChange={(e) => go({ location_id: e.target.value })}
                            className="rounded-md border border-border bg-background px-3 py-1.5 text-sm">
                            <option value="">Choose a location…</option>
                            {locationOptions.map((l) => <option key={l.id} value={l.id}>{l.name}</option>)}
                        </select>
                    </div>
                    {mode === 'radius' ? (
                        <div>
                            <label className="mb-1 block text-[11px] text-muted-foreground">Radius</label>
                            <select value={filters.radius} onChange={(e) => go({ radius: e.target.value })}
                                className="rounded-md border border-border bg-background px-3 py-1.5 text-sm">
                                {radii.map((r) => <option key={r} value={r}>{r} mi</option>)}
                            </select>
                        </div>
                    ) : (
                        <div>
                            <label className="mb-1 block text-[11px] text-muted-foreground">County</label>
                            <input value={filters.county ?? ''} onChange={(e) => go({ county: e.target.value })}
                                placeholder={center?.county ?? 'County'}
                                className="w-40 rounded-md border border-border bg-background px-3 py-1.5 text-sm" />
                        </div>
                    )}
                    <div className="relative">
                        <label className="mb-1 block text-[11px] text-muted-foreground">Search</label>
                        <Search className="pointer-events-none absolute bottom-2 left-2.5 size-4 text-muted-foreground" />
                        <input value={q} onChange={(e) => setQ(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && go({ q })}
                            placeholder="name, salon, address, ZIP, phone, license"
                            className="w-72 rounded-md border border-border bg-background py-1.5 pl-8 pr-3 text-sm" />
                    </div>
                    {mode === 'radius' && (
                        <div>
                            <label className="mb-1 block text-[11px] text-muted-foreground">ZIP</label>
                            <input value={filters.zip ?? ''} onChange={(e) => go({ zip: e.target.value })}
                                placeholder="All ZIPs" className="w-28 rounded-md border border-border bg-background px-3 py-1.5 text-sm" />
                        </div>
                    )}
                    <label className="flex items-center gap-1.5 pb-1.5 text-sm text-muted-foreground">
                        <input type="checkbox" checked={filters.hide_tenants}
                            onChange={(e) => go({ hide_tenants: e.target.checked ? 1 : 0, only_tenants: 0 })} />
                        Hide current tenants
                    </label>
                    <label className="flex items-center gap-1.5 pb-1.5 text-sm text-muted-foreground">
                        <input type="checkbox" checked={filters.only_tenants}
                            onChange={(e) => go({ only_tenants: e.target.checked ? 1 : 0, hide_tenants: 0 })} />
                        Show only current tenants
                    </label>
                    <button onClick={exportCsv} disabled={rows.length === 0}
                        className="ml-auto 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 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">
                    <Tile label="Total prospects" value={stats.total} />
                    <Tile label="Your tenants" value={stats.our_tenants} tone="amber" />
                    <Tile label="Other corp tenants" value={stats.other_corp_tenants} tone="blue" />
                    <Tile label="Already in Salesforce" value={stats.in_salesforce} tone="violet" />
                    <Tile label="Untouched leads" value={stats.untouched} tone="emerald" />
                    {mode === 'radius'
                        ? <Tile label="Center ZIP" value={stats.center_zip ?? '—'} />
                        : <Tile label="County" value={stats.county ?? '—'} />}
                </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-3 py-2.5 font-medium">Status</th>
                                <th className="px-3 py-2.5 font-medium">License #</th>
                                <th className="px-3 py-2.5 font-medium">Owner</th>
                                <th className="px-3 py-2.5 font-medium">Business</th>
                                <th className="px-3 py-2.5 font-medium">Competition</th>
                                <th className="px-3 py-2.5 font-medium">Address</th>
                                <th className="px-3 py-2.5 font-medium">City / State / ZIP</th>
                                <th className="px-3 py-2.5 font-medium">Phone</th>
                                {mode === 'radius'
                                    ? <th className="px-3 py-2.5 text-right font-medium">Distance</th>
                                    : <th className="px-3 py-2.5 font-medium">County</th>}
                                <th className="px-3 py-2.5 font-medium">Expiration</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-border">
                            {rows.map((r) => (
                                <tr key={r.id}>
                                    <td className="px-3 py-2.5"><StatusBadge status={r.status} detail={r.match_detail} /></td>
                                    <td className="px-3 py-2.5 text-muted-foreground">{r.license_number ?? '—'}</td>
                                    <td className="px-3 py-2.5 font-medium text-foreground">{r.owner ?? '—'}</td>
                                    <td className="px-3 py-2.5 text-muted-foreground">{r.business ?? '—'}</td>
                                    <td className="px-3 py-2.5 text-muted-foreground">
                                        {r.competition ?? '—'}
                                        {(r.suites_at_address ?? 0) > 1 && (
                                            <span className="ml-1 rounded bg-muted px-1 text-[10px]">{r.suites_at_address} suites</span>
                                        )}
                                    </td>
                                    <td className="px-3 py-2.5 text-muted-foreground">{r.address ?? '—'}</td>
                                    <td className="px-3 py-2.5 text-muted-foreground">{r.city_state_zip}</td>
                                    <td className="px-3 py-2.5 text-muted-foreground">{r.phone ?? '—'}</td>
                                    {mode === 'radius'
                                        ? <td className="px-3 py-2.5 text-right text-foreground">{r.distance ?? '—'}</td>
                                        : <td className="px-3 py-2.5 text-muted-foreground">{r.county ?? '—'}</td>}
                                    <td className={`px-3 py-2.5 ${r.expired ? 'font-medium text-destructive' : 'text-muted-foreground'}`}>
                                        {r.expiration ?? '—'}{r.expired && ' (expired)'}
                                    </td>
                                </tr>
                            ))}
                            {rows.length === 0 && (
                                <tr><td colSpan={10} className="px-3 py-12 text-center text-muted-foreground">
                                    No prospects. Import licence data with <code>php artisan prospects:import</code>, then choose a location.
                                </td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

function Tile({ label, value, tone }: { label: string; value: number | string; tone?: string }) {
    const tones: Record<string, string> = {
        amber: 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-300',
        blue: 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-300',
        violet: 'border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-500/30 dark:bg-violet-500/10 dark:text-violet-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">{typeof value === 'number' ? value.toLocaleString() : value}</p>
            <p className="mt-0.5 text-[10px] uppercase tracking-wide opacity-80">{label}</p>
        </div>
    );
}

function StatusBadge({ status, detail }: { status: string; detail: string | null }) {
    const tone = status === 'Your Tenant' ? 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300'
        : status === 'In Salesforce' ? 'bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300'
        : status === 'Other Corp Tenant' ? 'bg-blue-100 text-blue-700 dark:bg-blue-500/15 dark:text-blue-300'
        : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300';

    return (
        <span className={`inline-block rounded px-1.5 py-0.5 text-[11px] font-medium ${tone}`} title={detail ?? undefined}>
            {status}
        </span>
    );
}
