import { useMemo } from 'react';
import { Link } from '@tanstack/react-router';
import { Users } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { GroupTable } from '@/components/GroupTable';
import { useTournamentStore } from '@/stores/tournamentStore';
import { groupScenarios, type TeamScenario } from '@/lib/scenarios';
import { teamFlag } from '@/lib/teams';
import { fmt, useT } from '@/lib/i18n';
import type { Dict } from '@/lib/i18n';

function scenarioLabel(s: TeamScenario, t: Dict): { text: string; tone: string } {
  if (s.guaranteed) return { text: t.groups.scThrough, tone: 'text-accent' };
  if (!s.alive) return { text: t.groups.scOut, tone: 'text-faint line-through' };
  if (s.safeWithWin) return { text: t.groups.scWin, tone: 'text-ink' };
  return { text: fmt(t.groups.scAlive, { n: s.top2Count, total: s.totalCombos }), tone: 'text-muted' };
}

/** Final-round qualification scenarios under a group's table (top-2 only —
 *  third place runs through the cross-group best-thirds race). */
function Scenarios({ scenarios }: { scenarios: TeamScenario[] }) {
  const t = useT();
  return (
    <div className="rounded-b-xl border-x border-b border-line bg-surface-2 px-3 py-2">
      <div className="mb-1 text-[11px] font-bold uppercase tracking-wide text-faint">{t.groups.scenarios}</div>
      <ul className="space-y-0.5">
        {scenarios.map((s) => {
          const { text, tone } = scenarioLabel(s, t);
          return (
            <li key={s.team} className="flex items-center justify-between gap-2 text-xs">
              <span className="flex min-w-0 items-center gap-1.5 text-ink-soft">
                <span aria-hidden>{teamFlag(s.team)}</span>
                <span className="truncate">{s.team}</span>
              </span>
              <span className={`shrink-0 ${tone}`}>{text}</span>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

/** The cross-group race nobody can track by eye: every 3rd-placed team ranked
 *  by points/GD/goals — the top 8 advance to the Round of 32. */
function BestThirdsRace({ tables }: { tables: Record<string, import('@/lib/types').StandingRow[]> }) {
  const t = useT();
  const thirds = Object.entries(tables)
    .map(([g, rows]) => ({ g, r: rows.find((r) => r.rank === 3) }))
    .filter((x): x is { g: string; r: import('@/lib/types').StandingRow } => Boolean(x.r))
    .sort((a, b) => b.r.points - a.r.points || b.r.gd - a.r.gd || b.r.gf - a.r.gf || a.r.team.localeCompare(b.r.team));
  if (thirds.length < 12 || thirds.every((x) => x.r.played === 0)) return null;
  return (
    <div className="mt-6 rounded-xl border border-line bg-panel">
      <div className="border-b border-line px-4 py-2.5 font-display font-bold text-ink">{t.groups.thirdsRace}</div>
      <ul className="px-4 py-2">
        {thirds.map(({ g, r }, i) => (
          <li
            key={r.team}
            className={`flex items-center gap-2.5 border-b border-line/40 py-1.5 text-sm last:border-0 ${i < 8 ? '' : 'opacity-55'}`}
          >
            <span className={`w-5 shrink-0 text-right text-xs font-bold tabular-nums ${i < 8 ? 'text-gold' : 'text-faint'}`}>{i + 1}</span>
            <span aria-hidden className="shrink-0">{teamFlag(r.team)}</span>
            <Link to="/team/$name" params={{ name: r.team }} className="truncate font-medium text-ink hover:text-accent">{r.team}</Link>
            <span className="shrink-0 text-[11px] text-faint">{fmt(t.common.group, { group: g })}</span>
            <span className="tnum ml-auto shrink-0 text-xs text-muted">
              {r.played} · {r.gd > 0 ? `+${r.gd}` : r.gd} · <span className="font-bold text-ink">{r.points}</span>
            </span>
          </li>
        ))}
      </ul>
      <p className="border-t border-line px-4 py-2 text-[11px] text-faint">{t.groups.thirdsRaceNote}</p>
    </div>
  );
}

export function GroupsPage() {
  const t = useT();
  const snapshot = useTournamentStore((s) => s.snapshot);
  const tables = snapshot?.tables ?? {};
  const groups = Object.keys(tables).sort();

  const scenarioByGroup = useMemo(() => {
    const out: Record<string, TeamScenario[]> = {};
    if (!snapshot) return out;
    for (const g of Object.keys(tables)) {
      const rows = tables[g]!;
      const sc = groupScenarios(
        rows.map((r) => r.team),
        snapshot.fixtures.filter((f) => f.stage === 'group' && f.group === g),
      );
      if (sc) out[g] = sc;
    }
    return out;
  }, [snapshot, tables]);

  const anyScenarios = Object.keys(scenarioByGroup).length > 0;

  return (
    <div>
      <PageHeader
        title={t.groups.title}
        subtitle={t.groups.subtitle}
        actions={
          <Link to="/teams" className="inline-flex items-center gap-1.5 rounded-md border border-line px-3 py-1.5 text-sm font-medium text-muted hover:bg-elevated hover:text-ink">
            <Users size={15} /> {t.groups.allTeams}
          </Link>
        }
      />
      {groups.length ? (
        <div className="grid items-start gap-4 md:grid-cols-2 xl:grid-cols-3">
          {groups.map((g) => (
            <div key={g}>
              <GroupTable group={g} rows={tables[g]!} />
              {scenarioByGroup[g] && <Scenarios scenarios={scenarioByGroup[g]} />}
            </div>
          ))}
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="h-44 animate-pulse rounded-xl border border-line bg-panel" />
          ))}
        </div>
      )}

      <BestThirdsRace tables={tables} />

      <div className="mt-5 space-y-1.5 text-xs text-faint">
        <div className="flex items-center gap-4">
          <span className="inline-flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded bg-accent-glow ring-1 ring-accent-deep/40" /> {t.groups.legendTop2}
          </span>
          <span className="inline-flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded bg-gold/20 ring-1 ring-gold/40" /> {t.groups.legendThird}
          </span>
        </div>
        {anyScenarios && <p>{t.groups.scNote}</p>}
      </div>
    </div>
  );
}
