import type { BaseExerciseListProps } from '@/components/ExerciseList'
import ExerciseListComponent from '@/components/ExerciseList'
import { NonIdealState } from '@blueprintjs/core'
import type { Exercise } from '@inject/graphql/fragments/Exercise.generated'
import useExercisesSubscription from '@inject/graphql/utils/useExercisesSubscription'
import CenteredSpinner from '@inject/shared/components/CenteredSpinner'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'

type ExerciseListWrapperProps = BaseExerciseListProps & {
  filter?: (exercise: Exercise) => boolean
}

const ExerciseListWrapper: FC<ExerciseListWrapperProps> = ({
  filter,
  ...props
}) => {
  const { data, loading, error } = useExercisesSubscription()

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

  const exercises = data.exercises.filter(notEmpty).filter(filter || Boolean)
  if (exercises.length === 0) {
    return (
      <NonIdealState
        icon='low-voltage-pole'
        title='No exercise found'
        description='There are no exercises to display'
      />
    )
  }

  return <ExerciseListComponent {...props} exercises={exercises} />
}

export default ExerciseListWrapper
