import { useMutation } from '@apollo/react-hooks'

import { USER_LOGIN, CURRENT_USER } from './graphql'
import { useFormHandler, TextInput } from '../form/forms'
import { FormEvent } from 'react'


const initialValues = {
  email: 'tomislav.cvetic@u-blox.com',
  password: '1234'
}

const LoginForm = () => {

  const [login, { loading, error }] = useMutation(USER_LOGIN)
  const { inputProps, values } = useFormHandler(initialValues)

  return (
    <form onSubmit={async (event: FormEvent) => {
      event.preventDefault()
      try {
        const data = await login({
          variables: values,
          refetchQueries: [{ query: CURRENT_USER }]
        })
        console.log('LoginForm', data)
      } catch (error) {
        console.log('LoginForm', error)
      }
    }}>
      <TextInput label='Email' {...inputProps('email')} />
      <TextInput label='Password' {...inputProps('password')} />
      <button type='submit' disabled={loading}>Login!</button>
    </form>
  )
}

export default LoginForm
