import LinkButton from '@/components/LinkButton'
import { useNavigate } from '@/router'
import { Button, NonIdealState, Section, SectionCard } from '@blueprintjs/core'
import Reloader from '@inject/graphql/components/Reloader'
import { useGetExercise } from '@inject/graphql/queries/GetExercise.generated'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { useMemo } from 'react'
import { useLocation } from 'react-router-dom'
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 } = useGetExercise({
    variables: {
      exerciseId,
    },
    fetchPolicy: 'network-only',
  })
  const { name, userSet, teams: teamsDirty } = data?.exerciseId || {}
  const users = useMemo(() => userSet?.filter(notEmpty) || [], [userSet])
  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={<Reloader onRefetch={refetch} minimal />}
      >
        <SectionCard>
          <Instructors users={users} exerciseId={exerciseId} />
        </SectionCard>
        <SectionCard>
          <Teams teams={teams} exerciseId={exerciseId} />
        </SectionCard>
      </Section>

      {/* TODO: highlight or do not show already selected users */}
    </>
  )
}

export default ExerciseAssignment
