import { useState, useEffect } from 'react'

import { Password, User } from '../../types'
import '../../scss/form.scss'
import { useUserContext } from '../../contexts/UserContext'
import { useAppContext } from '../../contexts/AppContext'
import { useHistory } from 'react-router'
import { message } from 'antd'

export const UserForm = () => {
  const history = useHistory()
  const { api } = useAppContext()
  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)

      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 type="submit" disabled={!valid}>
          Save
        </button>
      </form>
    </>
  )
}
