import { createFileRoute, redirect } from "@tanstack/react-router";
import {
  tournamentQueries,
  useTournament,
} from "@/features/tournaments/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import GroupStageView from "@/features/tournaments/components/group-stage-view";
import { Container } from "@mantine/core";

export const Route = createFileRoute("/_authed/tournaments/$id/groups")({
  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} - Groups`,
    },
  }),
  component: RouteComponent,
});

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

  return (
    <Container size="md" px={0}>
      <GroupStageView
        groups={tournament.groups || []}
        matches={tournament.matches || []}
      />
    </Container>
  );
}
