import { useTrainingTypesQuery, TrainingType } from '../../gql'
import { Modal } from '../../modal'
import AddTrainingType from './AddTrainingType'
import { useState, useEffect } from 'react'

interface ITrainingTypeSelector {
  value?: TrainingType
  onChange: GenericEventHandler
  name?: string
  label?: string
}

const TrainingTypeSelector = ({
  value,
  onChange,
  name = 'type',
  label = 'Training type'
}: ITrainingTypeSelector) => {
  const [modalState, setModalState] = useState(false)
  const trainingTypes = useTrainingTypesQuery()
  const id = value?.id

  useEffect(() => {
    if (
      trainingTypes.data &&
      trainingTypes.data.trainingTypes.length > 0 &&
      !id
    ) {
      onChange({
        target: {
          type: 'custom',
          value: trainingTypes.data.trainingTypes[0],
          name
        }
      })
    }
  }, [trainingTypes.data])

  return (
    <>
      <label>{label}</label>
      <select
        id={name}
        name={name}
        value={id}
        onChange={event => {
          const copy: CustomChangeEvent = {
            target: {
              type: 'custom',
              value: { id: event.target.value },
              name
            }
          }
          onChange(copy)
        }}
      >
        {trainingTypes.loading && 'loading training types...'}
        {trainingTypes.error && 'error loading training types'}
        {trainingTypes.data &&
          trainingTypes.data.trainingTypes.map(trainingType => (
            <option key={trainingType.id} value={trainingType.id}>
              {trainingType.name}
            </option>
          ))}
      </select>
      <button
        type='button'
        onClick={event => {
          setModalState(true)
        }}
      >
        Add type
      </button>
      <Modal state={[modalState, setModalState]}>
        <AddTrainingType
          onSuccess={result => {
            setModalState(false)
            if (result.data) {
              onChange({
                target: {
                  type: 'custom',
                  value: { id: result.data.createTrainingType.id },
                  name
                }
              })
            }
          }}
        />
      </Modal>
    </>
  )
}
export default TrainingTypeSelector
