import { TextInput, useForm } from '../../form'
import {
  useCreateFormatMutation,
  FormatsDocument,
  CreateFormatMutation
} from '../../gql'
import { FetchResult } from '@apollo/client'

const CreateFormat = ({
  onSuccess
}: {
  onSuccess: (
    result: FetchResult<
      CreateFormatMutation,
      Record<string, any>,
      Record<string, any>
    >
  ) => void
}) => {
  const [createFormat, { data, error, loading }] = useCreateFormatMutation()
  const { values, touched, ...props } = useForm({
    name: '',
    description: ''
  })

  return (
    <form
      onSubmit={async event => {
        event.preventDefault()
        event.stopPropagation()
        const result = await createFormat({
          variables: values,
          refetchQueries: [{ query: FormatsDocument }]
        })
        if (result.data) onSuccess(result)
      }}
    >
      <h1>Add Format</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 CreateFormat
