import { useExercisesQuery } from '../../gql'
import { useState, useEffect } from 'react'
import { TExercise } from '../types'

interface IExerciseSelector {
  value?: TExercise
  onChange: GenericEventHandler
  name?: string
  label?: string
}

const ExerciseSelector = ({
  value,
  onChange,
  name = 'exercise',
  label = 'Exercise'
}: IExerciseSelector) => {
  const [state, setState] = useState(value?.id ?? '')
  const exercises = useExercisesQuery()

  useEffect(() => {
    setState(value?.id || '')
  }, [value])

  return (
    <>
      <label>{label}</label>
      <select
        id={name}
        name={name}
        value={state}
        onChange={ev => setState(ev.target.value)}
      >
        {exercises.loading && 'loading exercises...'}
        {exercises.error && 'error loading exercises'}
        {exercises.data &&
          exercises.data.exercises.map(exercise => (
            <option key={exercise.id} value={exercise.id}>
              {[exercise.name, exercise.description?.slice(0, 60)]
                .filter(exercise => !!exercise)
                .join(' - ')}
            </option>
          ))}
      </select>
      <button
        type='button'
        onClick={event => {
          const exercise =
            exercises.data &&
            exercises.data.exercises.find(exercise => exercise.id === state)
          if (!exercise) return
          const changeEvent: CustomChangeEvent = {
            target: {
              type: 'custom',
              value: exercise,
              name
            }
          }
          onChange(changeEvent)
        }}
      >
        Use
      </button>
    </>
  )
}

export default ExerciseSelector
