import type { Exercise } from '@inject/graphql/fragments/Exercise.generated'
import CardList from '@inject/shared/components/CardList'
import { type FC } from 'react'
import type { ManagingDetails, SelectingDetails } from './ExerciseCard'
import ExerciseCard from './ExerciseCard'

export type BaseExerciseListProps = {
  isSelected?: (exercise: Exercise) => boolean
  className?: string
} & (
  | {
      type: 'selecting'
      details: (exercise: Exercise) => SelectingDetails
    }
  | { type: 'managing'; details: (exercise: Exercise) => ManagingDetails }
)

type ExerciseListProps = BaseExerciseListProps & {
  exercises: Exercise[]
}

const ExerciseListComponent: FC<ExerciseListProps> = ({
  exercises,
  isSelected,
  type,
  details,
  className,
}) => (
  <CardList className={className}>
    {exercises.map(exercise =>
      type === 'selecting' ? (
        <ExerciseCard
          key={exercise.id}
          exercise={exercise}
          isSelected={isSelected ? isSelected(exercise) : undefined}
          type='selecting'
          details={details(exercise)}
        />
      ) : (
        <ExerciseCard
          key={exercise.id}
          exercise={exercise}
          type='managing'
          details={details(exercise)}
        />
      )
    )}
  </CardList>
)

export default ExerciseListComponent
