import { useMemo } from 'react';
import { Link } from '@tanstack/react-router';
import { Radio } from 'lucide-react';
import { PageHeader } from '@/components/ui/PageHeader';
import { MatchCard } from '@/components/MatchCard';
import { DailyDigest } from '@/components/DailyDigest';
import { useTournamentStore } from '@/stores/tournamentStore';
import { useFavoriteStore } from '@/stores/favoriteStore';
import { isToday } from '@/lib/format';
import { upcomingByDay, type DayGroup } from '@/lib/fixtures';
import { inPlayProbs } from '@/lib/model/inplay';
import { teamFlag } from '@/lib/teams';
import { fmt, useFormat } from '@/lib/i18n';
import type { Fixture } from '@/lib/types';

const UPCOMING_DAYS = 3;

/** The headline live match: big scoreboard card with a live win-probability
 *  bar (in-play when the score is known, else the pre-match model). */
function LiveHero({ f }: { f: Fixture }) {
  const { t } = useFormat();
  const pred = useTournamentStore((s) => s.model?.matches.find((m) => m.num === f.num));
  const probs = useMemo(() => {
    if (!pred) return null;
    if (f.homeScore != null && f.awayScore != null) {
      return inPlayProbs(pred.lambdaHome, pred.lambdaAway, f.minute ?? 0, f.homeScore, f.awayScore);
    }
    return pred.probs;
  }, [pred, f]);
  return (
    <section className="mb-7">
      <div className="mb-2.5 flex items-center gap-2">
        <span className="live-dot h-2 w-2 rounded-full bg-live" />
        <span className="text-xs font-bold uppercase tracking-[0.1em] text-live">{t.live.liveNowHeading}</span>
      </div>
      <Link
        to="/match/$num"
        params={{ num: String(f.num) }}
        className="block rounded-2xl border border-live/40 bg-gradient-to-br from-panel to-surface p-5 ring-1 ring-live/30 transition-colors hover:border-live/60"
      >
        <div className="mb-3.5 flex items-center justify-between gap-2 text-[11px] font-bold uppercase tracking-[0.1em]">
          <span className="truncate text-faint">
            {f.group ? fmt(t.common.group, { group: f.group }) : t.stage[f.stage]} · {f.venue}
          </span>
          <span className="tnum shrink-0 text-live">{f.minute ? fmt(t.live.minute, { n: f.minute }) : t.common.liveNow}</span>
        </div>
        <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3.5">
          <span className="flex min-w-0 items-center justify-end gap-2.5">
            <span className="truncate text-base font-bold text-ink md:text-[17px]">{f.home.label}</span>
            {f.home.team && <span aria-hidden className="text-3xl leading-none">{teamFlag(f.home.team)}</span>}
          </span>
          <span className="tnum text-3xl font-semibold tracking-[-0.03em] text-ink">
            {f.homeScore ?? 0}<span className="px-2 text-line-strong">–</span>{f.awayScore ?? 0}
          </span>
          <span className="flex min-w-0 items-center gap-2.5">
            {f.away.team && <span aria-hidden className="text-3xl leading-none">{teamFlag(f.away.team)}</span>}
            <span className="truncate text-base font-bold text-ink md:text-[17px]">{f.away.label}</span>
          </span>
        </div>
        {probs && (
          <div aria-hidden className="mt-4 flex h-[9px] gap-[2px] overflow-hidden rounded-full bg-elevated">
            <span className="bg-accent" style={{ width: `${probs.home * 100}%` }} />
            <span className="bg-faint" style={{ width: `${probs.draw * 100}%` }} />
            <span className="bg-info" style={{ width: `${probs.away * 100}%` }} />
          </div>
        )}
      </Link>
    </section>
  );
}

function Section({ title, fixtures }: { title: string; fixtures: Fixture[] }) {
  if (!fixtures.length) return null;
  return (
    <section className="mb-7">
      <h2 className="smallcaps mb-2.5">{title}</h2>
      <div className="grid gap-3 sm:grid-cols-2">
        {fixtures.map((f) => <MatchCard key={f.num} f={f} />)}
      </div>
    </section>
  );
}

export function LivePage() {
  const snapshot = useTournamentStore((s) => s.snapshot);
  const favorite = useFavoriteStore((s) => s.favorite);
  const { t, kickoffDay } = useFormat();

  // The starred team's next (or running) match, pinned on top.
  const favMatch = useMemo(() => {
    if (!favorite || !snapshot) return null;
    return snapshot.fixtures
      .filter((f) => f.status !== 'finished' && (f.home.team === favorite || f.away.team === favorite))
      .sort((a, b) => a.kickoff.localeCompare(b.kickoff))[0] ?? null;
  }, [favorite, snapshot]);

  const groups = useMemo(() => {
    const fixtures = snapshot?.fixtures ?? [];
    const live = fixtures.filter((f) => f.status === 'live').sort((a, b) => a.kickoff.localeCompare(b.kickoff));
    const today = fixtures
      .filter((f) => f.status !== 'live' && isToday(f.kickoff))
      .sort((a, b) => a.kickoff.localeCompare(b.kickoff));

    // The next few match days, each under its own day header.
    const upcoming: DayGroup[] = upcomingByDay(fixtures, UPCOMING_DAYS);

    const recent = fixtures
      .filter((f) => f.status === 'finished')
      .sort((a, b) => b.kickoff.localeCompare(a.kickoff))
      .slice(0, 6);

    return { live, today, upcoming, recent };
  }, [snapshot]);

  if (!snapshot) {
    return (
      <div>
        <PageHeader title={t.live.title} subtitle={t.live.loadingSubtitle} />
        <div className="grid gap-3 sm:grid-cols-2">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="h-24 animate-pulse rounded-xl border border-line bg-panel" />
          ))}
        </div>
      </div>
    );
  }

  const nothingNow = !groups.live.length && !groups.today.length;

  // The headline live card: the starred team's match when it's playing,
  // otherwise the earliest-kicked-off live match. The rest stay in the grid.
  const hero = (favorite && groups.live.find((m) => m.home.team === favorite || m.away.team === favorite)) || groups.live[0] || null;
  const otherLive = hero ? groups.live.filter((m) => m.num !== hero.num) : groups.live;

  return (
    <div>
      <PageHeader
        title={t.live.title}
        subtitle={fmt(t.live.subtitle, { season: snapshot.season })}
      />

      <DailyDigest />

      {hero && <LiveHero f={hero} />}

      {favMatch && favMatch.num !== hero?.num && (
        <section className="mb-7">
          <h2 className="smallcaps mb-2.5">★ {t.live.myTeam}</h2>
          <div className="grid gap-3 sm:grid-cols-2">
            <MatchCard f={favMatch} />
          </div>
        </section>
      )}

      <Section title={t.live.liveNowHeading} fixtures={otherLive} />
      <Section title={t.live.todayHeading} fixtures={groups.today} />
      {groups.upcoming.map((g, i) => (
        <Section
          key={g.key}
          title={i === 0 && nothingNow
            ? fmt(t.live.nextUpDay, { day: kickoffDay(g.firstKickoff) })
            : `${t.live.comingUp} · ${kickoffDay(g.firstKickoff)}`}
          fixtures={g.fixtures}
        />
      ))}
      <Section title={t.live.latestResults} fixtures={groups.recent} />

      {nothingNow && !groups.upcoming.length && !groups.recent.length && (
        <div className="grid place-items-center gap-2 rounded-xl border border-line bg-panel py-16 text-center text-muted">
          <Radio size={28} className="text-accent" />
          <p className="text-sm">{t.live.empty}</p>
        </div>
      )}
    </div>
  );
}
