import LinkButton from '@/components/LinkButton'
import TeamLabel from '@/components/TeamLabel'
import { useNavigate, useParams } from '@/router'
import { ButtonGroup, Classes, Tag } from '@blueprintjs/core'
import { ChevronRight } from '@blueprintjs/icons'
import useAuthIdentity from '@inject/graphql/auth'
import type { Team } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExercise } from '@inject/graphql/queries'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import { useEffect, useMemo } from 'react'

const TeamSelector = () => {
  const { exerciseId } = useParams('/trainee/:exerciseId')
  const nav = useNavigate()
  const [{ error, data, fetching }] = useTypedQuery({
    query: GetExercise,
    variables: {
      exerciseId,
    },
    requestPolicy: 'network-only',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const { id, isStaff } = useAuthIdentity()

  const exercise = data?.exerciseId

  useEffect(() => {
    if (!data?.exerciseId || fetching) return

    if (!fetching && data.exerciseId.teams.length === 1) {
      nav('/trainee/:exerciseId/:teamId', {
        params: {
          exerciseId: data.exerciseId.id,
          teamId: data.exerciseId.teams[0].id,
        },
      })
    }
  }, [fetching])

  if (!exercise) {
    return <p>None</p>
  }

  if (error) {
    return (
      <ErrorMessage>
        <h1>Error!</h1>
        <p>{error.message}</p>
      </ErrorMessage>
    )
  }

  return (
    <ButtonGroup vertical minimal>
      {exercise?.teams.map((team: Team) => (
        <LinkButton
          key={team.id}
          link={[
            '/trainee/:exerciseId/:teamId',
            { params: { exerciseId: exercise.id, teamId: team.id } },
          ]}
          button={{
            style: { padding: '1rem' },
            alignText: 'left',
            rightIcon: <ChevronRight className={Classes.TEXT_MUTED} />,
            children: (
              <>
                <TeamLabel
                  teamId={team.id}
                  teamName={team.name}
                  teamRole={team.role}
                />
                {isStaff && team.users.find(user => user.id === id) && (
                  <Tag round intent='warning'>
                    Assigned to
                  </Tag>
                )}
              </>
            ),
          }}
        />
      ))}
    </ButtonGroup>
  )
}

export default TeamSelector
