import LinkButton from '@/components/LinkButton'
import TeamLabel from '@/components/TeamLabel'
import {
  ButtonGroup,
  Classes,
  NonIdealState,
  Section,
  SectionCard,
} from '@blueprintjs/core'
import { ChevronRight } from '@blueprintjs/icons'
import Reloader from '@inject/graphql/components/Reloader'
import type { Team } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetRunningExercises } from '@inject/graphql/queries'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useMemo } from 'react'

const TeamSelector = () => {
  const [{ error, data }, refetch] = useTypedQuery({
    query: GetRunningExercises,
    requestPolicy: 'network-only',
  })

  const exercises = useMemo(
    () => (data?.exercises || []).filter(notEmpty),
    [data]
  )

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

  return (
    <Section
      title='Trainee Team Selection'
      rightElement={<Reloader minimal fill onRefetch={refetch} />}
    >
      {exercises.length === 0 && (
        <div style={{ padding: '1rem' }}>
          <NonIdealState
            icon='low-voltage-pole'
            description='There are no exercises active'
          />
        </div>
      )}
      {exercises.map(exercise => (
        <SectionCard padded key={exercise.id}>
          <h3
            style={{ paddingBottom: '1rem' }}
          >{`Exercise: ${exercise.name}`}</h3>
          <ButtonGroup vertical fill>
            {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}
                    />
                  ),
                }}
              />
            ))}
          </ButtonGroup>
        </SectionCard>
      ))}
    </Section>
  )
}

export default TeamSelector
