import LinkButton from '@/components/LinkButton'
import { useNavigate } from '@/router'
import {
  Button,
  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 { useLocation } from 'react-router-dom'
import CopyAssignment from './CopyAssignment'
import Instructors from './Instructors'
import Teams from './Teams'

interface ExerciseAssignmentProps {
  exerciseId: string
}

const ExerciseAssignment: FC<ExerciseAssignmentProps> = ({ exerciseId }) => {
  const nav = useNavigate()
  const { state } = useLocation()

  const [{ data }, refetch] = useTypedQuery({
    query: GetExercise,
    variables: {
      exerciseId,
    },
    requestPolicy: 'network-only',
  })
  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 (
    <>
      {state?.fromUserDetail ? (
        <Button
          type='button'
          minimal
          icon='chevron-left'
          onClick={() => {
            nav(-1)
          }}
        >
          Back
        </Button>
      ) : (
        <LinkButton
          link={['/exercise-panel']}
          button={{
            text: 'Back',
            icon: 'chevron-left',
            minimal: true,
          }}
        />
      )}

      <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
