import { useMemo } from "react";
import { Tournament } from "../../types";
import { useAuth } from "@/contexts/auth-context";
import { Box, Card, Center, Divider, Stack, Text } from "@mantine/core";
import { ClockIcon } from "@phosphor-icons/react";
import { isPredictionLocked, isTournamentPredictable } from "@/features/predictions/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { predictionQueries } from "@/features/predictions/queries";
import { useServerQuery } from "@/lib/tanstack-query/hooks";
import { Match } from "@/features/matches/types";
import Header from "./header";
import { Podium } from "../podium";
import SectionHeading from "./sections/section-heading";
import MatchCarousel from "./sections/match-carousel";
import ScoreReportCta from "./sections/score-report-cta";
import RecentResults from "./sections/recent-results";
import NavGrid from "./sections/nav-grid";

const teamPlayerIds = (t: Match["home"]): string[] =>
  t && typeof t !== "string" ? (t.players ?? []).map((p) => p.id) : [];

const StartedTournament: React.FC<{ tournament: Tournament }> = ({
  tournament,
}) => {
  const { user, roles } = useAuth();
  const { t } = useLingui();

  const isAdmin = useMemo(() => roles.includes("Admin"), [roles]);

  const matches = useMemo(() => tournament.matches || [], [tournament.matches]);

  const liveMatches = useMemo(
    () => matches.filter((m) => m.status === "started"),
    [matches]
  );

  const upcomingMatches = useMemo(
    () => matches.filter((m) => m.status === "ready" && m.home && m.away),
    [matches]
  );

  const endedMatches = useMemo(
    () =>
      matches
        .filter((m) => m.status === "ended")
        .sort(
          (a, b) =>
            new Date(b.end_time).getTime() - new Date(a.end_time).getTime()
        ),
    [matches]
  );

  const myLiveMatches = useMemo(
    () =>
      liveMatches.filter(
        (m) =>
          !!user?.id &&
          (teamPlayerIds(m.home).includes(user.id) ||
            teamPlayerIds(m.away).includes(user.id))
      ),
    [liveMatches, user?.id]
  );

  const isTournamentOver = useMemo(() => {
    if (matches.length === 0) return false;

    const nonByeMatches = matches.filter(
      (match) => !(match.status === "tbd" && match.bye === true)
    );
    if (nonByeMatches.length === 0) return false;

    const finalsMatch = nonByeMatches.reduce((highest, current) =>
      !highest || current.lid > highest.lid ? current : highest
    );

    return finalsMatch?.status === "ended";
  }, [matches]);

  const hasGroupStage = useMemo(
    () => matches.some((match) => match.round === -1),
    [matches]
  );

  const isPredictable = useMemo(
    () => isTournamentPredictable(tournament),
    [tournament]
  );

  const predictionsLocked = useMemo(
    () => isPredictionLocked(matches),
    [matches]
  );

  const { data: myPrediction } = useServerQuery({
    ...predictionQueries.mine(tournament.id),
    options: { enabled: isPredictable && !predictionsLocked },
  });
  const hasSubmitted = !!myPrediction?.prediction;

  const hasNoMatchContent =
    !isTournamentOver &&
    liveMatches.length === 0 &&
    upcomingMatches.length === 0 &&
    endedMatches.length === 0;

  return (
    <Stack gap="lg">
      <Header tournament={tournament} />

      <ScoreReportCta matches={myLiveMatches} />

      {isTournamentOver && (
        <Box>
          <SectionHeading label={t`Final Results`} />
          <Podium tournament={tournament} />
        </Box>
      )}

      {liveMatches.length > 0 && (
        <Box>
          <SectionHeading label={t`Live Matches`} live count={liveMatches.length} />
          <MatchCarousel matches={liveMatches} />
        </Box>
      )}

      {upcomingMatches.length > 0 && (
        <Box>
          <SectionHeading label={t`Upcoming`} count={upcomingMatches.length} />
          {/* SIDE BETS SLOT — see docs/side-bets.md */}
          <MatchCarousel matches={upcomingMatches} />
        </Box>
      )}

      <RecentResults matches={endedMatches} tournamentId={tournament.id} />

      {hasNoMatchContent && (
        <Card withBorder radius="lg" p="xl" mx="md">
          <Center>
            <Stack align="center" gap="md">
              <ClockIcon size={48} color="var(--mantine-color-dimmed)" />
              <Text size="lg" fw={500} c="dimmed">
                <Trans>No active matches</Trans>
              </Text>
            </Stack>
          </Center>
        </Card>
      )}

      <Box>
        <Divider mb="sm" />
        <NavGrid
          tournament={tournament}
          isAdmin={isAdmin}
          hasGroupStage={hasGroupStage}
          isPredictable={isPredictable}
          predictionsLocked={predictionsLocked}
          hasSubmitted={hasSubmitted}
        />
      </Box>
    </Stack>
  );
};

export default StartedTournament;
