import { NonIdealState, Section, SectionCard } from '@blueprintjs/core'
import { css } from '@emotion/css'
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 '.'
import Status from './Status'
import { canBeReviewed } from './utils'

const objectiveClass = css`
  flex-shrink: 0;
`

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

const InstructorQuestionnaireCard: FC<InstructorQuestionnaireCardProps> = ({
  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 (
    <Section
      key={details.id}
      title={details.title}
      className={objectiveClass}
      rightElement={
        <Status
          teamStateStatus={data.questionnaireState.status || 'UNSENT'}
          canBeReviewed={canBeReviewed(details.questions)}
        />
      }
      collapsible
    >
      <SectionCard padded>
        <InstructorQuestionnaire
          questionnaireId={details.id}
          teamId={teamId}
          exerciseId={exerciseId}
          status={data.questionnaireState.status}
          content={details.content}
          questions={details.questions}
          teamAnswers={data.questionnaireState.answers}
          relatedMilestones={data.questionnaireState.relatedMilestones}
          hideReview
        />
      </SectionCard>
    </Section>
  )
}

export default InstructorQuestionnaireCard
