import { createFileRoute, redirect } from "@tanstack/react-router";
import {
  tournamentQueries,
  useTournament,
} from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import { Container } from "@mantine/core";
import { useMemo } from "react";
import { BracketData } from "@/features/bracket/types";
import { groupMatchesIntoBracket } from "@/features/bracket/utils/group";
import BracketView from "@/features/bracket/components/bracket-view";
import { BracketPending } from "@/features/bracket/components/bracket-pending";

export const Route = createFileRoute("/_authed/tournaments/$id/bracket")({
  beforeLoad: async ({ context, params }) => {
    const { queryClient } = context;
    const tournament = await ensureServerQueryData(
      queryClient,
      tournamentQueries.details(params.id)
    );
    if (!tournament) throw redirect({ to: "/tournaments" });
    return {
      tournament,
    };
  },
  loader: ({ context }) => ({
    fullWidth: true,
    withPadding: false,
    header: {
      withBackButton: true,
      title: `${context.tournament.name}`,
    },
  }),
  component: RouteComponent,
  pendingComponent: BracketPending,
});

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

  const bracket: BracketData = useMemo(
    () => groupMatchesIntoBracket(tournament.matches),
    [tournament.matches]
  );

  return (
    <Container size="md" px={0}>
      <BracketView bracket={bracket} groupConfig={tournament.group_config} />
    </Container>
  );
}
