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

const Login = () => {
  const [user, setUser] = useState(INIT_USER)
  const [disabled, setDisabled] = useState(true)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const [id, setId] = useState('')

  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()
    try {
      // setLoading(true);
      // setError("");
      console.log('user정보:', user)
      const data = await userApi.login(user)
      console.log(data)
      setId(data.id)
      handleLogin(data.id)
      setSuccess(true)
    } catch (error) {
      console.log('error in login', error)
      catchErrors(error, setError)
    } finally {
      // setLoading(false);
    }
  }
  if (success) {
    alert('로그인 되었습니다');
    window.location.href = `/user/${id}`
  }

  const { email, password } = user

  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
        <div className="m-3 d-flex justify-content-center">
          <Link to="/">
            <img src="/BORA.png" style={{ width: '160px' }} />
          </Link>
        </div>
        <div className="row mt-5 d-flex align-items-center">
          <h2 style={{ textAlign: 'center' }}>로그인</h2>
          {error && <div className="alert alert-danger">{error}</div>}
          <div className="form-group">
            <div className="mt-5">
              <label>아이디</label>
              <input
                className="form-control"
                id="email"
                type="text"
                name="email"
                placeholder="아이디를 입력하세요"
                value={email}
                onChange={handleChange}
              />
            </div>
            <div className="mt-3">
              <label>비밀번호</label>
              <input
                className="form-control"
                id="password"
                type="password"
                name="password"
                placeholder="비밀번호를 입력하세요"
                value={password}
                onChange={handleChange}
              />
            </div>
          </div>
          <div className="mt-4 d-flex justify-content-center">
            <button
              type="submit"
              className="btn btn-primary"
              disabled={disabled}
            >
              로그인
            </button>
          </div>
        </div>
      </form>
    </div>
  )
}

export default Login
