import { SyntheticEvent } from "react"
import { useMutation } from "@apollo/client"

import { useFormHandler, TextInput } from "../form/forms"

import { CURRENT_USER, USER_EDIT } from "./graphql"
import { UserProps } from "./props"
import { userValidation } from "./validation"

const initialData = {
  name: '',
  email: '',
  password: '',
  passwordAgain: ''
}

const UserEditForm = ({ user }: UserProps) => {
  const [updateUser, userEdit] = useMutation(USER_EDIT)
  const { inputProps, values } = useFormHandler({ ...initialData, ...user })

  return (
    <form onSubmit={async (event: SyntheticEvent) => {
      event.preventDefault()
      await updateUser({ variables: values, refetchQueries: [{ query: CURRENT_USER }] })
    }}>
      <TextInput label='Name' {...inputProps('name')} />
      <TextInput label='Email' {...inputProps('email')} />
      <TextInput label='Password' {...inputProps('password')} />
      <TextInput label='Repeat password' {...inputProps('passwordAgain')} />
      <button type='submit' disabled={userEdit.loading}>Update</button>
    </form>
  )
}

export default UserEditForm