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 { Box, Card, Container, Group, Skeleton, SimpleGrid, Stack } 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}`,
    },
  }),
  component: RouteComponent,
  pendingComponent: GroupsPending,
});

function GroupsPending() {
  return (
    <Container size="md" px={0}>
      <Box p="md">
        <Stack gap="md">
          <Group gap={0} grow mb="md">
            {Array.from({ length: 4 }).map((_, index) => (
              <Skeleton
                key={`groups-pending-tab-${index}`}
                height={44}
                radius="sm"
                style={{ opacity: 0.85 - index * 0.1 }}
              />
            ))}
          </Group>
          <Card withBorder radius="md" p={0}>
            <Group justify="space-between" p="sm">
              <Skeleton height={16} width={120} radius="sm" />
              <Skeleton height={22} width={22} radius="xl" />
            </Group>
          </Card>
          <SimpleGrid cols={{ base: 1, sm: 2, lg: 3 }} spacing="md">
            {Array.from({ length: 6 }).map((_, index) => (
              <Skeleton
                key={`groups-pending-match-${index}`}
                height={100}
                radius="md"
                style={{ opacity: Math.max(1 - index * 0.12, 0.4) }}
              />
            ))}
          </SimpleGrid>
        </Stack>
      </Box>
    </Container>
  );
}

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

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