import { TextInput, useForm } from '../../form'
import {
  useCreateTrainingTypeMutation,
  TrainingTypesDocument,
  CreateTrainingTypeMutation
} from '../../gql'
import { FetchResult } from '@apollo/client'

const AddTrainingType = ({
  onSuccess
}: {
  onSuccess: (
    result: FetchResult<
      CreateTrainingTypeMutation,
      Record<string, any>,
      Record<string, any>
    >
  ) => void
}) => {
  const [
    createTrainingType,
    { data, error, loading }
  ] = useCreateTrainingTypeMutation()
  const { values, touched, ...props } = useForm({
    name: '',
    description: ''
  })

  return (
    <form
      onSubmit={async event => {
        event.preventDefault()
        event.stopPropagation()
        const result = await createTrainingType({
          variables: values,
          refetchQueries: [{ query: TrainingTypesDocument }]
        })
        if (result.data) onSuccess(result)
      }}
    >
      <h1>Add Training Type</h1>
      <TextInput name='name' label='Name' value={values.name} {...props} />
      <TextInput
        name='description'
        label='Description'
        value={values.description}
        {...props}
      />
      <button type='submit'>Save</button>
      {error && <span className='error'>{error.message}</span>}

      <style jsx>
        {`
          form {
            max-width: 700px;
          }
        `}
      </style>
    </form>
  )
}

export default AddTrainingType
