import { useEffect, useState } from 'react'
import { Redirect } from 'react-router-dom'
import userApi from '../apis/user.api'
import catchErrors from "../context/catchError";
import { handleLogin } from '../context/auth';
const INIT_USER = {
  email: '',
  password: '',
}

const Login = () => {
  // const { loading, login, catchErrorAuth } = useAuth()
  const [user, setUser] = useState(INIT_USER)
  const [disabled, setDisabled] = useState(true)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  useEffect(() => {
    const isUser = Object.values(user).every((el) => Boolean(el))
    isUser ? setDisabled(false) : setDisabled(true)
  }, [user])

  function handleChange(event) {
    const { name, value } = event.target
    setUser({ ...user, [name]: value })
  }

  async function handleSubmit(e) {
    e.preventDefault()
    console.log('로그인')
    try {
      // setLoading(true);
      // setError("");
      const data = await userApi.login(user)
      console.log(data)
      handleLogin(data.id)
      setSuccess(true)
    } catch (error) {
      console.log('error in login', error)
      catchErrors(error, setError)
    } finally {
      // setLoading(false);
    }
  }
  if (success) {
    alert('로그인 되었습니다')
    return <Redirect to="/user" />
  }

  const { email, password } = user

  return (
    <div className="modal-content">
      {error && <div className="alert alert-danger">{error}</div>}
      <form onSubmit={handleSubmit}>
        <div className="modal-header">
          <h5 className="modal-title" id="loginModalLabel">
            로그인
          </h5>
          <button
            type="button"
            className="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div className="modal-body">
          <div>
            <label>아이디</label>
            <input
              className="form-control"
              id="email"
              type="text"
              name="email"
              placeholder="아이디를 입력하세요"
              value={email}
              onChange={handleChange}
            />
          </div>
          <div>
            <label>비밀번호</label>
            <input
              className="form-control"
              id="password"
              type="password"
              name="password"
              placeholder="비밀번호를 입력하세요"
              value={password}
              onChange={handleChange}
            />
          </div>
        </div>
        <div className="modal-footer">
          <button
            type="submit"
            className="btn btn-primary"
            disabled={disabled}
            data-bs-dismiss="modal"
          >
            로그인
          </button>
        </div>
      </form>
    </div>
  )
}

export default Login
