import { lazy, Suspense, useMemo } from 'react';
import { TrendingUp, Trophy } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { Card, CardBody, CardHeader } from '@/components/ui/Card';
import { OddsTable } from '@/components/OddsTable';
import { WinProbBar } from '@/components/WinProbBar';

// Recharts is heavy and only used here — load it as a separate on-demand chunk.
const OddsChart = lazy(() => import('@/components/OddsChart').then((m) => ({ default: m.OddsChart })));
import { teamFlag } from '@/lib/teams';
import { kickoffDay, kickoffTime } from '@/lib/format';
import { useTournamentStore } from '@/stores/tournamentStore';

function ChampionBoard({ odds }: { odds: { team: string; champion: number }[] }) {
  const top = odds.slice(0, 8);
  const max = Math.max(...top.map((t) => t.champion), 0.01);
  return (
    <div className="space-y-2">
      {top.map((t, i) => (
        <div key={t.team} className="flex items-center gap-3">
          <span className="w-4 text-right text-xs font-bold tabular-nums text-faint">{i + 1}</span>
          <span aria-hidden className="text-lg leading-none">{teamFlag(t.team)}</span>
          <span className="w-28 shrink-0 truncate text-sm font-medium text-ink">{t.team}</span>
          <div className="h-3 flex-1 overflow-hidden rounded-full bg-elevated">
            <div
              className="h-full rounded-full bg-gradient-to-r from-accent-deep to-accent"
              style={{ width: `${(t.champion / max) * 100}%` }}
            />
          </div>
          <span className="tnum w-12 shrink-0 text-right text-sm font-bold text-ink">
            {(t.champion * 100).toFixed(1)}%
          </span>
        </div>
      ))}
    </div>
  );
}

export function PredictionsPage() {
  const model = useTournamentStore((s) => s.model);
  const snapshot = useTournamentStore((s) => s.snapshot);

  const upcoming = useMemo(() => {
    if (!model || !snapshot) return [];
    const fxByNum = new Map(snapshot.fixtures.map((f) => [f.num, f]));
    return model.matches
      .map((m) => ({ m, f: fxByNum.get(m.num)! }))
      .filter(({ f }) => f && f.status !== 'finished')
      .sort((a, b) => a.f.kickoff.localeCompare(b.f.kickoff))
      .slice(0, 8);
  }, [model, snapshot]);

  if (!model) {
    return (
      <div>
        <PageHeader title="Predict" subtitle="Running the simulation…" />
        <div className="h-64 animate-pulse rounded-xl border border-line bg-panel" />
      </div>
    );
  }

  return (
    <div>
      <PageHeader
        title="Predict"
        subtitle={`Elo + Dixon-Coles + ${model.iterations.toLocaleString()} Monte Carlo simulations · ratings as of ${model.asOf}`}
      />

      <div className="mb-6 grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader className="flex items-center gap-2">
            <Trophy size={16} className="text-gold" />
            <span className="font-display font-bold text-ink">Who lifts the trophy?</span>
          </CardHeader>
          <CardBody>
            <ChampionBoard odds={model.odds} />
          </CardBody>
        </Card>

        <Card>
          <CardHeader className="flex items-center gap-2">
            <TrendingUp size={16} className="text-accent" />
            <span className="font-display font-bold text-ink">Title race over time</span>
          </CardHeader>
          <CardBody>
            {model.history.length >= 2 ? (
              <Suspense fallback={<div className="h-72 animate-pulse rounded-lg bg-elevated" />}>
                <OddsChart history={model.history} />
              </Suspense>
            ) : (
              <div className="grid h-72 place-items-center text-center text-sm text-muted">
                <p className="max-w-xs">
                  The title-race chart fills in as results come in — each completed match re-rates
                  the teams and re-runs the simulation.
                </p>
              </div>
            )}
          </CardBody>
        </Card>
      </div>

      <h2 className="smallcaps mb-2.5">Full odds — group, knockout & title</h2>
      <div className="mb-6">
        <OddsTable odds={model.odds} />
      </div>

      {upcoming.length > 0 && (
        <>
          <h2 className="smallcaps mb-2.5">Next match predictions</h2>
          <div className="grid gap-3 sm:grid-cols-2">
            {upcoming.map(({ m, f }) => (
              <Card key={m.num}>
                <CardBody className="space-y-2">
                  <div className="flex items-center justify-between text-[11px] text-faint">
                    <span>{f.group ? `Group ${f.group}` : f.round}</span>
                    <span>{kickoffDay(f.kickoff)} · {kickoffTime(f.kickoff)}</span>
                  </div>
                  <WinProbBar home={m.home} away={m.away} probs={m.probs} topScore={m.topScore} />
                </CardBody>
              </Card>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
