import { useMemo } from 'react';
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 { fmt, useFormat } from '@/lib/i18n';
import type { Fixture } from '@/lib/types';

const UPCOMING_DAYS = 3;

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;

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

      <DailyDigest />

      {favMatch && (
        <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={groups.live} />
      <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>
  );
}
