import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, Legend, ReferenceLine } from 'recharts';
import { PortfolioTabs, LocationFilter } from '@/components/portfolio/PortfolioTabs';
import { TrendingUp } from 'lucide-react';

type Trend = { buckets: string[]; series: Record<string, number[]>; totals: Record<string, number> };
type Funnel = { key: string; label: string; percent: number; detail: string; highlight?: boolean };
type Velocity = { label: string; hours?: number | null; sample?: number | null; count?: number; warn?: boolean };
type Projection = {
    rows: { month: string; source_month: string; leads: number; scheduled_tours: number; completed_tours: number; leases_signed: number }[];
    baseline: number; rates: { scheduled: number; completed: number; signed: number };
};
type PaidVsOrg = {
    paid_average: number; organic_average: number; ratio: number | null;
    google_average: number; facebook_average: number; paid_target: number; above_target: string[];
    by_source: Record<string, number>; buckets: string[]; paid: number[]; org: number[];
};

const VIEWS = [
    { key: 'overview', label: 'Overview' },
    { key: 'leads', label: 'Total Leads' },
    { key: 'scheduled_tours', label: 'Scheduled Tours' },
    { key: 'completed_tours', label: 'Completed Tours' },
    { key: 'leases_signed', label: 'Leases Signed' },
    { key: 'paid_vs_org', label: 'Paid vs Org' },
];

const COLORS: Record<string, string> = {
    leads: '#C99A2E', scheduled_tours: '#3B82F6', completed_tours: '#10B981',
    leases_signed: '#8B5CF6', paid: '#DC2626', org: '#10B981',
};

export default function PipelineAnalytics() {
    const props = usePage().props as unknown as {
        trend: Trend; funnel: Funnel[]; velocity: Velocity[]; projection: Projection;
        paidVsOrg: PaidVsOrg; months: number; granularity: string; location: string | null;
        locationOptions: { id: number; name: string }[];
    };
    const { trend, funnel, velocity, projection, paidVsOrg, months, granularity, location, locationOptions } = props;
    const [view, setView] = useState('overview');

    const go = (params: Record<string, string | number>) =>
        router.get('/portfolio/pipeline-analytics',
            { months, granularity, location: location ?? '', ...params }, { preserveState: true });

    const chartData = trend.buckets.map((b, i) => ({
        bucket: b,
        leads: trend.series.leads[i],
        scheduled_tours: trend.series.scheduled_tours[i],
        completed_tours: trend.series.completed_tours[i],
        leases_signed: trend.series.leases_signed[i],
        paid: paidVsOrg.paid[i],
        org: paidVsOrg.org[i],
    }));

    const lines = view === 'overview'
        ? ['leads', 'scheduled_tours', 'completed_tours', 'leases_signed']
        : view === 'paid_vs_org' ? ['paid', 'org'] : [view];

    return (
        <>
            <Head title="Pipeline Analytics" />
            <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">
                        <TrendingUp className="size-5 text-primary" /> Pipeline Analytics
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        {location ?? 'All locations'} — trailing {months} months
                    </p>
                </header>

                <PortfolioTabs />

                <div className="mb-4 flex flex-wrap items-center gap-2">
                    <LocationFilter options={locationOptions} value={location} onChange={(v) => go({ location: v })} />
                    <div className="flex overflow-hidden rounded-md border border-border">
                        {VIEWS.map((v) => (
                            <button key={v.key} onClick={() => setView(v.key)}
                                className={`px-3 py-1.5 text-xs font-medium transition ${view === v.key ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}>
                                {v.label}
                            </button>
                        ))}
                    </div>
                    <div className="ml-auto flex gap-1">
                        {[3, 6, 12, 24].map((m) => (
                            <button key={m} onClick={() => go({ months: m })}
                                className={`rounded-md px-2.5 py-1.5 text-xs font-medium ${months === m ? 'bg-primary text-primary-foreground' : 'border border-border hover:bg-muted'}`}>
                                {m} mo
                            </button>
                        ))}
                    </div>
                    <div className="flex gap-1">
                        {['month', 'week'].map((g) => (
                            <button key={g} onClick={() => go({ granularity: g })}
                                className={`rounded-md px-2.5 py-1.5 text-xs font-medium capitalize ${granularity === g ? 'bg-primary text-primary-foreground' : 'border border-border hover:bg-muted'}`}>
                                {g}
                            </button>
                        ))}
                    </div>
                </div>

                {view === 'paid_vs_org' && (
                    <div className="mb-3 flex flex-wrap gap-4 text-xs">
                        <span className="text-destructive">Paid average: <strong>{paidVsOrg.paid_average}</strong></span>
                        <span className="text-emerald-600">Organic average: <strong>{paidVsOrg.organic_average}</strong></span>
                        {paidVsOrg.ratio !== null && <span className="text-muted-foreground">Paid : Org ratio: <strong>{paidVsOrg.ratio}</strong></span>}
                        {Object.entries(paidVsOrg.by_source).slice(0, 4).map(([src, avg]) => (
                            <span key={src} className="text-muted-foreground">{src} avg: <strong>{avg}</strong></span>
                        ))}
                    </div>
                )}

                <div className="mb-6 rounded-xl border border-border bg-card p-5">
                    <ResponsiveContainer width="100%" height={320}>
                        <LineChart data={chartData}>
                            <XAxis dataKey="bucket" tick={{ fontSize: 11 }} />
                            <YAxis tick={{ fontSize: 11 }} width={40} />
                            <Tooltip />
                            <Legend />
                            {view === 'paid_vs_org' && (
                                <>
                                    <ReferenceLine y={paidVsOrg.paid_target} stroke="#C99A2E" strokeWidth={2}
                                        label={{ value: 'target', position: 'right', fontSize: 10 }} />
                                    <ReferenceLine y={paidVsOrg.paid_average} stroke="#DC2626" strokeDasharray="4 4" />
                                    <ReferenceLine y={paidVsOrg.organic_average} stroke="#10B981" strokeDasharray="4 4" />
                                </>
                            )}
                            {lines.map((k) => (
                                <Line key={k} type="monotone" dataKey={k} stroke={COLORS[k] ?? 'var(--primary)'}
                                    strokeWidth={2} name={k.replace(/_/g, ' ')}
                                    dot={k === 'paid'
                                        ? (props: any) => (paidVsOrg.above_target.includes(props.payload.bucket)
                                            ? <text key={props.key} x={props.cx} y={props.cy + 6} textAnchor="middle" fontSize={16} fill="#C99A2E">★</text>
                                            : <circle key={props.key} cx={props.cx} cy={props.cy} r={3} fill="#DC2626" />)
                                        : { r: 3 }} />
                            ))}
                        </LineChart>
                    </ResponsiveContainer>
                    <div className="mt-3 flex flex-wrap gap-5 text-sm">
                        <Legend2 color={COLORS.leads} label="Total Leads" value={trend.totals.leads} />
                        <Legend2 color={COLORS.scheduled_tours} label="Scheduled Tours" value={trend.totals.scheduled_tours} />
                        <Legend2 color={COLORS.completed_tours} label="Completed Tours" value={trend.totals.completed_tours} />
                        <Legend2 color={COLORS.leases_signed} label="Leases Signed" value={trend.totals.leases_signed} />
                    </div>
                </div>

                <h2 className="mb-2 font-semibold text-foreground">Conversion Funnel</h2>
                <div className="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
                    {funnel.map((f) => (
                        <div key={f.key} className={`rounded-xl border p-4 ${f.highlight
                            ? 'border-amber-300 bg-amber-50 dark:border-amber-500/30 dark:bg-amber-500/10'
                            : 'border-border bg-accent/20'}`}>
                            <p className="text-2xl font-semibold text-foreground">{f.percent}%</p>
                            <p className="mt-1 text-xs font-medium text-foreground">{f.label}</p>
                            <p className="mt-0.5 text-[11px] text-muted-foreground">{f.detail}</p>
                        </div>
                    ))}
                </div>

                <h2 className="mb-2 font-semibold text-foreground">Lead Velocity</h2>
                <div className="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
                    {velocity.map((v) => (
                        <div key={v.label} className={`rounded-xl border p-4 ${v.warn
                            ? 'border-orange-300 bg-orange-50 dark:border-orange-500/30 dark:bg-orange-500/10'
                            : 'border-emerald-200 bg-emerald-50 dark:border-emerald-500/30 dark:bg-emerald-500/10'}`}>
                            <p className="text-2xl font-semibold text-foreground">
                                {v.count !== undefined ? v.count : (v.hours ?? '—')}
                                {v.hours !== undefined && v.hours !== null && <span className="ml-1 text-sm font-normal text-muted-foreground">hrs</span>}
                            </p>
                            <p className="mt-1 text-xs font-medium text-foreground">{v.label}</p>
                            {v.sample ? <p className="mt-0.5 text-[11px] text-muted-foreground">{v.sample} leads</p> : null}
                        </div>
                    ))}
                </div>

                <h2 className="mb-1 font-semibold text-foreground">Projected — next 12 months</h2>
                <p className="mb-3 text-xs text-muted-foreground">
                    Baseline {projection.baseline} leads (median of recent complete months), scaled by prior-year
                    month-over-month change · Rates: Scheduled {projection.rates.scheduled}% ·
                    Completed {projection.rates.completed}% · Signed {projection.rates.signed}%
                </p>
                <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">Month</th>
                                <th className="px-4 py-2.5 text-left font-medium">Source month</th>
                                <th className="px-4 py-2.5 text-right font-medium">Leads</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">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">
                            {projection.rows.map((r) => (
                                <tr key={r.month}>
                                    <td className="px-4 py-2.5 font-medium text-foreground">{r.month}</td>
                                    <td className="px-4 py-2.5 text-muted-foreground">{r.source_month}</td>
                                    <td className="px-4 py-2.5 text-right text-foreground">{r.leads}</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.completed_tours}</td>
                                    <td className="px-4 py-2.5 text-right font-medium text-emerald-600">{r.leases_signed}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}

function Legend2({ color, label, value }: { color: string; label: string; value: number }) {
    return (
        <span className="flex items-center gap-1.5">
            <span className="size-2.5 rounded-full" style={{ background: color }} />
            <span className="text-foreground">{label} <strong>({value.toLocaleString()})</strong></span>
        </span>
    );
}
