import Page from '@/components/page'
import { Stack } from '@mantine/core'
import { createFileRoute } from '@tanstack/react-router'
import { TournamentCard } from '@/features/tournaments/components/tournament-card'
import { tournamentQueries } from '@/features/tournaments/queries'
import { useQuery } from '@tanstack/react-query'
import { useAuth } from '@/contexts/auth-context'
import { useSheet } from '@/hooks/use-sheet'
import Sheet from '@/components/sheet/sheet'
import CreateTournament from '@/features/admin/components/create-tournament'
import { PlusIcon } from '@phosphor-icons/react'
import Button from '@/components/button'

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

function RouteComponent() {
  const { data: tournaments } = useQuery(tournamentQueries.list());
  const { roles } = useAuth();
  const sheet = useSheet();

  return <Page>
    <Stack>
      {
        roles?.includes("Admin") ? (
          <>
          <Button leftSection={<PlusIcon />} variant='subtle' onClick={sheet.open}>Create Tournament</Button>
          <Sheet {...sheet.props} title='Create Tournament'>
            <CreateTournament close={sheet.close} />
          </Sheet>
          </>
        ) : null
      }
      {
        tournaments?.map((tournament: any) => (
          <TournamentCard key={tournament.id} tournament={tournament} />
        ))
      }
    </Stack>
  </Page>
}
