import { createFileRoute } from '@tanstack/react-router'
import { tournamentQueries } from '@/features/tournaments/queries';
import Page from '@/components/page'
import { useQuery } from '@tanstack/react-query';
import { Box, Button } from '@mantine/core';
import { useSheet } from '@/hooks/use-sheet';
import Sheet from '@/components/sheet/sheet';
import { Tournament } from '@/features/tournaments/types';
import { UsersIcon } from '@phosphor-icons/react';
import ListButton from '@/components/list-button';
import TeamList from '@/features/teams/components/team-list';

export const Route = createFileRoute('/_authed/tournaments/$tournamentId')({
  beforeLoad: async ({ context, params }) => {
    const { queryClient } = context;
    await queryClient.ensureQueryData(tournamentQueries.details(params.tournamentId))
  },
  loader: ({ params }) => ({
    header: {
      collapsed: true,
      withBackButton: true
    },
    refresh: {
      toRefresh: tournamentQueries.details(params.tournamentId).queryKey,
    }
  }),
  component: RouteComponent,
})

function RouteComponent() {
  const { data: tournament } = useQuery(tournamentQueries.details(Route.useParams().tournamentId));

  const sheet = useSheet()

  return <Page noPadding>
    <Box mt='xl' p='md'>

      <h3 style={{ marginTop: 0 }}>
        {tournament?.name}
      </h3>

      <Button onClick={() => sheet.open()}>
        View Teams
      </Button>

    </Box>

    <ListButton
      label='Teams'
      onClick={() => sheet.open()}
      Icon={UsersIcon}
    />

    <Sheet
      {...sheet.props}
      title='Teams'
    >
      <TeamDrawer tournament={tournament!} />
    </Sheet>
  </Page>
}

const TeamDrawer = ({ tournament }: { tournament: Tournament }) => {
  return (
    <TeamList teams={tournament?.teams!} />
  );
}
