import React, { useMemo } from "react";
import {
  ActionIcon,
  Box,
  Button,
  Divider,
  Group,
  Popover,
  Stack,
  Text,
  ThemeIcon,
  Title,
  UnstyledButton,
} from "@mantine/core";
import { CrownIcon, InfoIcon } from "@phosphor-icons/react";
import WizardOrbIcon from "@/components/wizard-orb-icon";
import { Plural, Trans, useLingui } from "@lingui/react/macro";
import { useNavigate } from "@tanstack/react-router";
import { Tournament } from "@/features/tournaments/types";
import PlayerAvatar from "@/components/player-avatar";
import { useServerQuery } from "@/lib/tanstack-query/hooks";
import { predictionQueries, usePredictionsLeaderboard } from "../queries";
import { isPredictionLocked, isTournamentPredictable } from "../utils";

interface PredictionLeaderboardProps {
  tournament: Tournament;
}

export const PredictionLeaderboard: React.FC<PredictionLeaderboardProps> = ({
  tournament,
}) => {
  const { t } = useLingui();
  const navigate = useNavigate();
  const { data: leaderboard } = usePredictionsLeaderboard(tournament.id);

  const matches = tournament.matches || [];
  const isComplete = useMemo(() => {
    const nonByeMatches = matches.filter(
      (match) => !(match.status === "tbd" && match.bye === true)
    );
    return (
      nonByeMatches.length > 0 &&
      nonByeMatches.every((match) => match.status === "ended")
    );
  }, [matches]);

  const predictionsOpen =
    isTournamentPredictable(tournament) && !isPredictionLocked(matches);

  const { data: myPrediction } = useServerQuery({
    ...predictionQueries.mine(tournament.id),
    options: { enabled: !leaderboard.locked && predictionsOpen },
  });

  if (!leaderboard.locked) {
    const cta = predictionsOpen ? (
      <Button
        onClick={() =>
          navigate({
            to: "/tournaments/$id/predictions/make",
            params: { id: tournament.id },
          })
        }
      >
        {myPrediction?.prediction ? (
          <Trans>Edit Your Prediction</Trans>
        ) : (
          <Trans>Make Your Prediction</Trans>
        )}
      </Button>
    ) : undefined;

    return (
      <Stack gap={0}>
        <Stack align="center" gap="md" py="xl">
          <WizardOrbIcon
            size={56}
            weight="duotone"
            color="var(--mantine-primary-color-filled)"
          />
          <Stack align="center" gap={4}>
            <Title order={3} c="dimmed" ta="center">
              <Trans>Predictions are open</Trans>
            </Title>
            <Text size="sm" c="dimmed" ta="center" maw={280}>
              <Trans>
                Other players' predictions are hidden until the tournament
                starts.
              </Trans>
            </Text>
          </Stack>
          {cta}
        </Stack>
        {leaderboard.submitters.length > 0 && (
          <>
            <Text px="md" size="sm" fw={600} pb="xs">
              <Plural
                value={leaderboard.count}
                one="# bracket in"
                other="# brackets in"
              />
            </Text>
            {leaderboard.submitters.map((player, index) => {
              const name = `${player.first_name} ${player.last_name}`;
              return (
                <Box key={player.id}>
                  <Group gap="sm" align="center" p="md" wrap="nowrap">
                    <PlayerAvatar name={name} size={32} disableFullscreen />
                    <Text size="sm" fw={600} lineClamp={1}>
                      {name}
                    </Text>
                  </Group>
                  {index < leaderboard.submitters.length - 1 && <Divider />}
                </Box>
              );
            })}
          </>
        )}
      </Stack>
    );
  }

  if (leaderboard.entries.length === 0) {
    return (
      <Stack align="center" gap="md" py="xl">
        <WizardOrbIcon
          size={56}
          weight="duotone"
          color="var(--mantine-primary-color-filled)"
        />
        <Stack align="center" gap={4}>
          <Title order={3} c="dimmed" ta="center">
            <Trans>No predictions</Trans>
          </Title>
          <Text size="sm" c="dimmed" ta="center" maw={280}>
            <Trans>Nobody made a prediction for this tournament.</Trans>
          </Text>
        </Stack>
      </Stack>
    );
  }

  return (
    <Stack gap={0}>
      <Group px="md" justify="space-between" align="center" wrap="nowrap">
        <Text size="lg" fw={600}>
          <Trans>Predictions</Trans>
        </Text>
        <Popover position="bottom-end" withArrow shadow="md">
          <Popover.Target>
            <ActionIcon
              variant="subtle"
              size="sm"
              aria-label={t`How prediction scoring works`}
            >
              <InfoIcon size={14} />
            </ActionIcon>
          </Popover.Target>
          <Popover.Dropdown>
            <Box maw={280}>
              <Text size="sm" fw={500} mb="xs">
                <Trans>Prediction Scoring:</Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>
                  • Each correct pick earns points, doubling every round
                </Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>
                  • <strong>Winners bracket:</strong> 10, 20, 40, 80…
                </Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>
                  • <strong>Losers bracket:</strong> 5, 10, 20, 40…
                </Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>
                  • <strong>Bracket reset:</strong> only picked if your
                  bracket triggers it — worth double the Final
                </Trans>
              </Text>

              <Divider my="sm" />

              <Text size="sm" fw={500} mb="xs">
                <Trans>Tiebreakers:</Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>1. Correct champion pick</Trans>
              </Text>
              <Text size="xs" mb={2}>
                <Trans>2. Earlier submission</Trans>
              </Text>
              <Text size="xs" mt="xs" c="dimmed">
                <Trans>* PICKS shows correct picks / total picks made</Trans>
              </Text>
            </Box>
          </Popover.Dropdown>
        </Popover>
      </Group>
      <Text px="md" c="dimmed" size="xs" fw={500}>
        <Trans>Correct picks are worth more each round</Trans>
      </Text>
      {leaderboard.entries.map((entry, index) => {
        const name = `${entry.player.first_name} ${entry.player.last_name}`;

        return (
          <Box key={entry.player.id}>
            <UnstyledButton
              w="100%"
              p="md"
              style={{ borderRadius: 0 }}
              onClick={() =>
                navigate({
                  to: "/tournaments/$id/predictions/$playerId",
                  params: { id: tournament.id, playerId: entry.player.id },
                })
              }
            >
              <Group justify="space-between" align="center" w="100%" wrap="nowrap">
                <Group gap="sm" align="center" wrap="nowrap">
                  <PlayerAvatar name={name} size={40} disableFullscreen />
                  <Stack gap={2}>
                    <Group gap="xs" wrap="nowrap">
                      <Text size="xs" c="dimmed">
                        #{index + 1}
                      </Text>
                      <Text size="sm" fw={600} lineClamp={1}>
                        {name}
                      </Text>
                      {index === 0 && isComplete && (
                        <ThemeIcon size="xs" color="yellow" variant="light" radius="xl">
                          <CrownIcon size={12} />
                        </ThemeIcon>
                      )}
                    </Group>
                    {entry.championPick && (
                      <Group gap={4} wrap="nowrap">
                        <CrownIcon
                          size={12}
                          weight="fill"
                          color={
                            entry.championCorrect && isComplete
                              ? "gold"
                              : "var(--mantine-color-dimmed)"
                          }
                        />
                        <Text size="xs" c="dimmed" lineClamp={1}>
                          {entry.championPick.name}
                        </Text>
                      </Group>
                    )}
                  </Stack>
                </Group>
                <Group gap="md" wrap="nowrap">
                  <Stack gap={0} ta="center">
                    <Text size="xs" c="dimmed" fw={700}>
                      <Trans>PTS</Trans>
                    </Text>
                    <Text size="sm" fw={700}>
                      {entry.points}
                    </Text>
                  </Stack>
                  <Stack gap={0} ta="center">
                    <Text size="xs" c="dimmed" fw={700}>
                      <Trans>PICKS</Trans>
                    </Text>
                    <Text size="xs" c="dimmed">
                      {entry.correct}/{entry.total}
                    </Text>
                  </Stack>
                </Group>
              </Group>
            </UnstyledButton>
            {index < leaderboard.entries.length - 1 && <Divider />}
          </Box>
        );
      })}
    </Stack>
  );
};
