import { useEffect } from 'react'
import { useTrainingQuery, useCreateTrainingMutation } from '../../gql'
import { useForm } from '../../form'
import { emptyTraining } from '../constants'
import TrainingInputs from './TrainingInputs'

const EditTraining = ({ id = '' }: { id?: string }) => {
  const trainingData = useTrainingQuery({ variables: { id } })

  const { values, touched, onChange, loadData } = useForm(emptyTraining)
  const [createTraining, createData] = useCreateTrainingMutation()

  useEffect(() => {
    console.log('training effect', trainingData)
    if (trainingData.data?.training) loadData(trainingData.data.training)
  }, [trainingData.data])

  return (
    <>
      <form
        onSubmit={ev => {
          ev.preventDefault()
          //createTraining({ variables: values })
        }}
      >
        <TrainingInputs name='test' values={values} onChange={onChange} />
        <button type='submit' disabled={createData.loading}>
          Save
        </button>
        {createData.data && <span color='green'>Saved.</span>}
        {createData.error && (
          <span color='red'>Error saving: {createData.error.message}</span>
        )}
      </form>
    </>
  )
}

export default EditTraining
