import { useEffect, useState, type ReactNode } from 'react';
import { Activity, Dices, Gauge, TrendingUp } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { Card, CardBody, CardHeader } from '@/components/ui/Card';
import { Term } from '@/components/ui/Term';
import { ReliabilityDiagram } from '@/components/ReliabilityDiagram';
import { fmt, fmtSplit, useFormat, useT } from '@/lib/i18n';
import type { BacktestReport } from '@/lib/types';

const STEP_ICONS = [TrendingUp, Activity, Gauge, Dices] as const;

function RpsBar({ label, rps, best, highlight }: { label: string; rps: number; best: number; highlight?: boolean }) {
  const t = useT();
  // shorter bar = better (lower RPS). Scale relative to the worst (uniform ~0.24).
  const width = Math.min(100, (rps / 0.26) * 100);
  return (
    <div className="flex items-center gap-3 text-sm">
      <span className={`w-28 shrink-0 ${highlight ? 'font-bold text-ink' : 'text-muted'}`}>{label}</span>
      <div className="h-4 flex-1 overflow-hidden rounded bg-elevated">
        <div className={`h-full rounded ${highlight ? 'bg-gradient-to-r from-accent-deep to-accent' : 'bg-line-strong'}`} style={{ width: `${width}%` }} />
      </div>
      <span className={`tnum w-12 text-right ${highlight ? 'font-bold text-accent' : 'text-faint'}`}>{rps.toFixed(3)}</span>
      {rps === best && <span className="text-[10px] font-bold uppercase text-accent">{t.methodology.backtest.bestBadge}</span>}
    </div>
  );
}

function Stat({ value, label }: { value: string; label: string }) {
  return (
    <div className="text-center">
      <div className="font-display text-2xl font-extrabold text-ink">{value}</div>
      <div className="text-[11px] uppercase tracking-wide text-faint">{label}</div>
    </div>
  );
}

export function MethodologyPage() {
  const { t, locale } = useFormat();
  const [bt, setBt] = useState<BacktestReport | null>(null);

  useEffect(() => {
    let alive = true;
    fetch('/data/backtest.json').then((r) => r.json()).then((d: BacktestReport) => alive && setBt(d)).catch(() => {});
    return () => { alive = false; };
  }, []);

  const bestRps = bt ? Math.min(bt.model.rps, bt.baselines.uniform.rps, bt.baselines.baseRate.rps, bt.baselines.eloOnly.rps) : 0;

  const steps = [t.methodology.steps.elo, t.methodology.steps.goalModels, t.methodology.steps.scorelines, t.methodology.steps.monteCarlo]
    .map((s, i) => ({ ...s, icon: STEP_ICONS[i] ?? TrendingUp }));

  const introParts = bt
    ? fmtSplit(
        fmt(
          bt.validation
            ? t.methodology.backtest.intro
            : t.methodology.backtest.intro.replace(/\{valFrom\}.*?\{valTo\}/, t.methodology.backtest.validationFallback),
          {
            trainEnd: bt.trainEnd.slice(0, 4),
            testFrom: (bt.testFrom ?? bt.trainEnd).slice(0, 4),
            testTo: bt.testTo.slice(0, 4),
            ...(bt.validation ? { valFrom: bt.validation.from.slice(0, 4), valTo: bt.validation.to.slice(0, 4) } : {}),
          },
        ),
      )
    : [];

  const metricsParts = fmtSplit(t.methodology.backtest.metricsLine);
  const metricsNodes: Record<string, ReactNode> = {
    rps: <Term k="RPS" />,
    brier: <Term k="Brier" />,
    ece: <Term k="ECE" />,
    ensemble: <Term k="ensemble" />,
  };

  return (
    <div className="space-y-6">
      <PageHeader title={t.methodology.title} subtitle={t.methodology.subtitle} />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {steps.map((s, i) => (
          <Card key={s.title}>
            <CardBody>
              <div className="mb-2 flex items-center gap-2">
                <span className="grid h-7 w-7 place-items-center rounded-md bg-accent-glow text-accent"><s.icon size={16} /></span>
                <span className="text-xs font-bold text-faint">{fmt(t.methodology.stepLabel, { n: i + 1 })}</span>
              </div>
              <h3 className="font-display font-bold text-ink">{s.title}</h3>
              <p className="mt-1 text-sm text-muted">{s.body}</p>
            </CardBody>
          </Card>
        ))}
      </div>

      <Card>
        <CardHeader><span className="font-display font-bold text-ink">{t.methodology.backtest.heading}</span></CardHeader>
        <CardBody className="space-y-5">
          {bt ? (
            <>
              <p className="text-sm text-muted">
                {introParts.map((p, i) =>
                  typeof p === 'string'
                    ? p
                    : p.key === 'tested'
                      ? <span key={i} className="font-semibold text-ink">{bt.tested.toLocaleString(locale === 'de' ? 'de-DE' : 'en-GB')}</span>
                      : null,
                )}
              </p>
              <div className="grid grid-cols-3 gap-3 rounded-lg border border-line bg-surface-2 py-3">
                <Stat value={`${(bt.model.accuracy * 100).toFixed(0)}%`} label={t.methodology.backtest.stats.outcomeAccuracy} />
                <Stat value={bt.model.rps.toFixed(3)} label={t.methodology.backtest.stats.rps} />
                <Stat value={`${(bt.worldCup.accuracy * 100).toFixed(0)}%`} label={fmt(t.methodology.backtest.stats.worldCupAccuracy, { n: bt.worldCup.tested })} />
              </div>
              <p className="text-xs text-faint">
                {metricsParts.map((p, i) => (typeof p === 'string' ? p : <span key={i}>{metricsNodes[p.key] ?? null}</span>))}
              </p>
              <div>
                <div className="mb-2 text-xs uppercase tracking-wide text-faint">{t.methodology.backtest.rpsChartHeading}</div>
                <div className="space-y-1.5">
                  {(bt.variants ?? [{ name: t.methodology.backtest.thisModel, ...bt.model }]).map((v, i) => (
                    <RpsBar key={v.name} label={v.name} rps={v.rps} best={bestRps} highlight={i === 0} />
                  ))}
                  <RpsBar label={t.methodology.backtest.baseRates} rps={bt.baselines.baseRate.rps} best={bestRps} />
                  <RpsBar label={t.methodology.backtest.coinFlip} rps={bt.baselines.uniform.rps} best={bestRps} />
                </div>
              </div>
            </>
          ) : (
            <div className="h-32 animate-pulse rounded bg-elevated" />
          )}
        </CardBody>
      </Card>

      <Card>
        <CardHeader><span className="font-display font-bold text-ink">{t.methodology.calibration.heading}</span></CardHeader>
        <CardBody>
          {bt ? <ReliabilityDiagram reliability={bt.reliability} ece={bt.ece} /> : <div className="h-64 animate-pulse rounded bg-elevated" />}
        </CardBody>
      </Card>

      <Card>
        <CardHeader><span className="font-display font-bold text-ink">{t.methodology.limits.heading}</span></CardHeader>
        <CardBody>
          <ul className="space-y-2 text-sm text-muted">
            <li>• {t.methodology.limits.notAdvice}</li>
            <li>• {t.methodology.limits.sparseData}</li>
            <li>• {t.methodology.limits.variance}</li>
            <li>• {t.methodology.limits.openData}</li>
          </ul>
        </CardBody>
      </Card>
    </div>
  );
}
