import axios from 'axios'
import { useEffect, useState } from 'react'
import { Link, Redirect } from 'react-router-dom'
import userApi from '../apis/user.api'
import catchErrors from '../context/catchError'

const INIT_USER = {
  name: '',
  email: '',
  password: '',
  checkpw: '',
  phone: '',
}

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

  useEffect(() => {
    setDisabled(!(user.name && user.email && user.password && user.checkpw))
  }, [user])

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

  async function handleSubmit(e) {
    e.preventDefault()
    console.log('회원가입')
    try {
      if (checkPassword()) {
        const data = await userApi.signup(user)
        console.log(data)
        setSuccess(true)
        setError('')
      }
    } catch (error) {
      console.log('error')
      catchErrors(error, setError)
    } finally {
      setLoading(false);
    }
  }
  function checkPassword(event) {
    const p1 = user.password
    const p2 = user.checkpw
    if (p1 !== p2) {
      // event.preventDefault()
      alert('비밀번호가 일치하지 않습니다.')
      window.location.href = '/login'
      return false
    } else {
      // alert('회원가입 되었습니다.')
      // window.location.href = '/'
      return true
    }
  }

  if(success) {
    alert('회원가입 되었습니다.')
    window.location.href = '/'
  }

  const { name, id, password, checkpw, phone } = user
  return (
    <div className="container">
      {error && <div className="alert alert-danger">{error}</div>}
      <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-4">
          <h5 style={{ textAlign: 'center' }}>회원가입</h5>
        </div>
        <div className="form-group">
          <div className="p-2">
            <label className="p-1">이름</label>
            <input
              className="form-control"
              id="name"
              type="text"
              name="name"
              placeholder="이름을 입력하세요"
              value={name}
              onChange={handleChange}
            />
          </div>
          <div className="p-2">
            <label className="p-1">아이디</label>
            <input
              className="form-control"
              id="text"
              type="text"
              name="email"
              placeholder="아이디를 입력하세요"
              value={id}
              onChange={handleChange}
            />
          </div>
          <div className="p-2">
            <label className="p-1">비밀번호</label>
            <input
              className="form-control"
              id="password"
              type="password"
              name="password"
              placeholder="비밀번호를 입력하세요"
              value={password}
              onChange={handleChange}
            />
          </div>
          <div className="p-2">
            <label className="p-1">비밀번호확인</label>
            <input
              className="form-control"
              id="checkpw"
              type="password"
              name="checkpw"
              placeholder="비밀번호를 다시 입력하세요"
              value={checkpw}
              onChange={handleChange}
            />
          </div>
          <div className="p-2">
            <label className="p-1">전화번호</label>
            <input
              className="form-control"
              id="phone"
              type="text"
              name="phone"
              placeholder="'-'을 제외하고 입력하세요"
              value={phone}
              onChange={handleChange}
            />
          </div>
          {/* {console.log(disabled)} */}
          <div className="mt-3 d-flex justify-content-center">
          <button
            type="submit"
            className="btn btn-primary"
            onClick={handleSubmit}
            disabled={disabled}
          >
            회원가입
          </button>
        </div>
        </div>
      </form>
    </div>
  )
}

export default Signup
