import { NonIdealState } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTeamLearningObjectives } from '@inject/graphql/queries'
import Container from '@inject/shared/components/Container'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useMemo, type FC } from 'react'
import LearningObjective from './LearningObjective'

const wrapper = css`
  display: flex;
  flex-direction: column;
  gap: 2rem;
  padding: 1rem;
  overflow-y: auto;
`

interface LearningObjectivesProps {
  teamId: string
}

const LearningObjectives: FC<LearningObjectivesProps> = ({ teamId }) => {
  const [{ data, error }] = useTypedQuery({
    query: GetTeamLearningObjectives,
    variables: { teamId },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })

  const objectives = useMemo(
    () =>
      (data?.teamLearningObjectives?.filter(notEmpty) ?? []).sort(
        (a, b) => a.objective.order - b.objective.order
      ),
    [data]
  )

  if (error) {
    return (
      <ErrorMessage>
        <h1>Error occurred!</h1>
        <p>{error.message}</p>
      </ErrorMessage>
    )
  }

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

  return (
    <Container className={wrapper}>
      {objectives.map(objective => (
        <LearningObjective
          key={objective.id}
          objective={objective}
          teamId={teamId}
        />
      ))}
    </Container>
  )
}

export default LearningObjectives
