import { createFileRoute, redirect } from "@tanstack/react-router";
import { tournamentQueries } from "@/features/tournaments/queries";
import ManageTeams from "@/features/teams/components/manage-teams";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import { Box, Divider, Group, Skeleton, Stack } from "@mantine/core";
import { msg } from "@lingui/core/macro";

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

function ManageTeamsPending() {
  return (
    <Stack gap="xs">
      <Box px="md">
        <Skeleton height={42} radius="sm" />
      </Box>
      <Box px="md">
        <Skeleton height={12} width={90} radius="sm" />
      </Box>
      <Stack gap={0}>
        {Array.from({ length: 8 }).map((_, index) => (
          <div key={`manage-teams-skeleton-${index}`} style={{ opacity: Math.max(1 - index * 0.1, 0.35) }}>
            <Group p="xs" wrap="nowrap" w="100%">
              <Skeleton height={40} width={40} radius="sm" />
              <Skeleton height={16} width="45%" radius="sm" />
              <Stack ml="auto" gap={6} align="flex-end">
                <Skeleton height={10} width={90} radius="sm" />
                <Skeleton height={10} width={70} radius="sm" />
              </Stack>
            </Group>
            <Divider />
          </div>
        ))}
      </Stack>
    </Stack>
  );
}

function RouteComponent() {
  const { id } = Route.useParams();
  const { tournament } = Route.useRouteContext();
  return <ManageTeams tournament={tournament} />;
}