import { createFileRoute, redirect } from "@tanstack/react-router";
import { Trans } from "@lingui/react/macro";
import { msg } from "@lingui/core/macro";
import { useMemo } from "react";
import { Box, Container, Group, Paper, Stack, Text } from "@mantine/core";
import { tournamentQueries, useTournament } from "@/features/tournaments/queries";
import { predictionQueries, usePlayerPrediction } from "@/features/predictions/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import { BracketPending } from "@/features/bracket/components/bracket-pending";
import { PredictionBracket } from "@/features/predictions/components/prediction-bracket";
import { computePredictionScore } from "@/features/predictions/utils";
import PlayerAvatar from "@/components/player-avatar";

export const Route = createFileRoute(
  "/_authed/tournaments/$id/predictions_/$playerId"
)({
  beforeLoad: async ({ context, params }) => {
    const { queryClient } = context;
    const tournament = await ensureServerQueryData(
      queryClient,
      tournamentQueries.details(params.id)
    );
    if (!tournament) throw redirect({ to: "/tournaments" });

    const prediction = await ensureServerQueryData(
      queryClient,
      predictionQueries.player(params.id, params.playerId)
    );
    if (!prediction) {
      throw redirect({
        to: "/tournaments/$id/predictions",
        params: { id: params.id },
      });
    }

    return {
      tournament,
      prediction,
    };
  },
  loader: ({ context }) => ({
    fullWidth: true,
    withPadding: false,
    header: {
      withBackButton: true,
      title: msg`{name}'s Bracket`,
      titleValues: { name: context.prediction.player.first_name },
    },
  }),
  component: RouteComponent,
  pendingComponent: BracketPending,
});

function RouteComponent() {
  const { id, playerId } = Route.useParams();
  const { data: tournament } = useTournament(id);
  const { data: prediction } = usePlayerPrediction(id, playerId);

  const matches = tournament.matches || [];
  const picks = prediction?.picks ?? {};

  const score = useMemo(
    () => computePredictionScore(matches, picks),
    [matches, picks]
  );

  return (
    <Container size="md" px={0}>
      <Box pos="relative">
        <PredictionBracket
          matches={matches}
          picks={picks}
          mode="view"
          perMatch={score.perMatch}
        />

        <Box
          pos="absolute"
          left={0}
          right={0}
          bottom={0}
          p="md"
          style={{ zIndex: 2, pointerEvents: "none" }}
        >
          <Paper
            withBorder
            shadow="md"
            radius="lg"
            p="sm"
            style={{ pointerEvents: "auto" }}
          >
            <Group justify="space-between" align="center" wrap="nowrap">
              <Group gap="sm" align="center" wrap="nowrap">
                <PlayerAvatar
                  name={`${prediction?.player.first_name} ${prediction?.player.last_name}`}
                  size={32}
                  disableFullscreen
                />
                <Text size="sm" fw={600} lineClamp={1}>
                  {prediction?.player.first_name} {prediction?.player.last_name}
                </Text>
              </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}>
                    {score.points}
                  </Text>
                </Stack>
                <Stack gap={0} ta="center">
                  <Text size="xs" c="dimmed" fw={700}>
                    <Trans>PICKS</Trans>
                  </Text>
                  <Text size="xs" c="dimmed">
                    {score.correct}/{score.total}
                  </Text>
                </Stack>
              </Group>
            </Group>
          </Paper>
        </Box>
      </Box>
    </Container>
  );
}
