import ExerciseContext from '@/analyst/ExerciseContext'
import TeamSelectPage from '@/analyst/TeamSelectPage'
import LearningObjective from '@/instructor/LearningObjectives/LearningObjective'
import { NonIdealState } from '@blueprintjs/core'
import type { Team } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseLearningObjectives } from '@inject/graphql/queries'
import CenteredSpinner from '@inject/shared/components/CenteredSpinner'
import { useCallback, useContext, useMemo } from 'react'

export const Pending = () => <CenteredSpinner />

const Page = () => {
  const { exercise } = useContext(ExerciseContext)

  const [{ data }] = useTypedQuery({
    query: GetExerciseLearningObjectives,
    variables: { exerciseId: exercise.id },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  const getChildren = useCallback(
    (selectedTeam: Team) => {
      const objectives =
        data?.exerciseLearningObjectives?.filter(objective =>
          objective.teams.map(team => team.id).includes(selectedTeam.id)
        ) || []

      if (objectives.length === 0) {
        return (
          <NonIdealState
            icon='low-voltage-pole'
            title='No learning objectives'
            description='There are no learning objectives in this exercise'
          />
        )
      }

      return objectives.map(objective => (
        <LearningObjective
          key={objective.id}
          objective={objective}
          teamId={selectedTeam.id}
          disabled
        />
      ))
    },
    [data?.exerciseLearningObjectives]
  )

  return <TeamSelectPage teams={exercise.teams} getChildren={getChildren} />
}

export default Page
