import { useState, useEffect } from 'react'

import { Password, User } from '../../types'
import { useUserContext } from '../../contexts/UserContext'
import { message } from 'antd'
import { Button } from '../../elements/Button'

export const UserForm = () => {
  const { user } = useUserContext()

  console.log(user)

  const [name, setName] = useState(user?.name)
  const [email, setEmail] = useState(user?.email)
  const [password, setPassword] = useState('')
  const [passwordConfirm, setPasswordConfirm] = useState('')
  const [valid, setValid] = useState(false)

  useEffect(() => {
    passwordConfirm.length > 4 && password === passwordConfirm && name && email
      ? setValid(true)
      : setValid(false)
  }, [password, passwordConfirm, name, email])

  // @ts-ignore
  const handleSubmit = async (e) => {
    e.preventDefault()

    if (!name || !email) {
      message.error('Name and email required!')
      return
    }

    const body: Omit<User, 'id'> & Password = {
      name,
      email,
      password,
      passwordConfirm,
    }

    try {
      // user?.id
      // ? await api.updateUser(user.id, body)
      // : await api.createUser(body)
      console.log('User form wtf')
      // if (!user?.id) history.push('/login')
    } catch (err) {
      message.error('Something went wrong')
    }
  }

  return (
    <>
      <h1>{user?.id ? 'Edit' : 'Create'} Profile</h1>
      <form className="dank-form" onSubmit={handleSubmit}>
        <label>
          Name: <input value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <label>
          Email:
          <input
            value={email}
            type="email"
            onChange={(e) => setEmail(e.target.value)}
          />
        </label>
        <label>
          Password:
          <input
            value={password}
            type="password"
            onChange={(e) => setPassword(e.target.value)}
          />
        </label>
        <label>
          Confirm Password:
          <input
            type="password"
            onChange={(e) => setPasswordConfirm(e.target.value)}
          />
        </label>
        <Button htmlType="submit" disabled={!valid}>
          Save
        </Button>
      </form>
    </>
  )
}
