import { NonIdealState } from '@blueprintjs/core'
import type { QuestionnaireDetails } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTeamQuestionnaireState } from '@inject/graphql/queries'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import { useMemo, type FC } from 'react'
import InstructorQuestionnaire from '.'

interface InstructorQuestionnaireContentProps {
  details: QuestionnaireDetails
  teamId: string
  exerciseId: string
}

const InstructorQuestionnaireContent: FC<
  InstructorQuestionnaireContentProps
> = ({ details, teamId, exerciseId }) => {
  const [{ data, error }] = useTypedQuery({
    query: GetTeamQuestionnaireState,
    variables: {
      teamId,
      questionnaireId: details.id,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  if (error) {
    return (
      <ErrorMessage>
        <h1>Error occurred!</h1>
        <p>{error.message}</p>
      </ErrorMessage>
    )
  }
  if (!data || !data.questionnaireState) {
    return (
      <NonIdealState
        icon='low-voltage-pole'
        title='No data'
        description='Please wait for the data to come in'
      />
    )
  }

  return (
    <InstructorQuestionnaire
      exerciseId={exerciseId}
      questionnaireId={details.id}
      teamId={teamId}
      status={data.questionnaireState.status}
      content={details.content}
      questions={details.questions}
      teamAnswers={data.questionnaireState.answers}
      relatedMilestones={data.questionnaireState.relatedMilestones}
    />
  )
}

export default InstructorQuestionnaireContent
