import {
  ButtonGroup,
  Divider,
  NonIdealState,
  Section,
  SectionCard,
} from '@blueprintjs/core'
import Reloader from '@inject/graphql/components/Reloader'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExercise } from '@inject/graphql/queries'
import responsiveButtonGroup from '@inject/shared/css/responsiveButtonGroup'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { useMemo } from 'react'
import CopyAssignment from './CopyAssignment'
import Instructors from './Instructors'
import Teams from './Teams'

interface ExerciseAssignmentProps {
  exerciseId: string
}

const ExerciseAssignment: FC<ExerciseAssignmentProps> = ({ exerciseId }) => {
  const [{ data }, refetch] = useTypedQuery({
    query: GetExercise,
    variables: {
      exerciseId,
    },
    requestPolicy: 'network-only',
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const { name, instructors, teams: teamsDirty } = data?.exerciseId || {}
  const users = useMemo(() => instructors || [], [instructors])
  const teams = useMemo(() => teamsDirty?.filter(notEmpty) || [], [teamsDirty])

  if (!data || !data.exerciseId) {
    return (
      <NonIdealState
        icon='low-voltage-pole'
        description='Unable to display participants'
      />
    )
  }

  return (
    <Section
      title='Manage participants of exercise'
      subtitle={name}
      rightElement={
        <ButtonGroup minimal className={responsiveButtonGroup}>
          <CopyAssignment exerciseId={exerciseId} teamCount={teams.length} />
          <Divider />
          <Reloader onRefetch={refetch} minimal />
        </ButtonGroup>
      }
    >
      <SectionCard padded>
        <Instructors users={users} exerciseId={exerciseId} />
      </SectionCard>
      <SectionCard padded>
        <Teams teams={teams} exerciseId={exerciseId} />
      </SectionCard>
    </Section>
  )
  /* TODO: highlight or do not show already selected users */
}

export default ExerciseAssignment
