import ExerciseContext from '@/analyst/ExerciseContext'
import TeamSelectPage from '@/analyst/TeamSelectPage'
import InstructorQuestionnaireCard from '@/instructor/InstructorQuestionnaire/InstructorQuestionnaireCard'
import { NonIdealState } from '@blueprintjs/core'
import type { Team } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseQuestionnaires } 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: GetExerciseQuestionnaires,
    variables: { exerciseId: exercise.id },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  const getChildren = useCallback(
    (selectedTeam: Team) => {
      const questionnaires = data?.questionnaires || []

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

      return questionnaires.map(questionnaire => {
        const teamState = questionnaire.teamQuestionnaireStates.find(
          teamState => teamState.team.id === selectedTeam.id
        )

        if (!teamState) return null

        return (
          <InstructorQuestionnaireCard
            key={questionnaire.id}
            teamState={teamState}
            questionnaire={questionnaire}
            teamId={selectedTeam.id}
            exerciseId={exercise.id}
            collapsible
            hideReview
          />
        )
      })
    },
    [data?.questionnaires, exercise.id]
  )

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

export default Page
