import React from "react";
import { useNavigate, useLocation } from "react-router";


import Join from "./../join/Join.jsx";
import passwordChange from "./../main/PasswordChange.jsx";
import Button from "../../component/Button.jsx";


export default function Login() {
  const navigate = useNavigate();
  const location = useLocation();

  //로그인 정보
  const [loginInfo, setLoginInfo] = React.useState({ 'user_id': '', 'user_password': '' });
  //사용자의 입력으로 인한 로그인 정보 변경
  const loginInfoChange = (key, value) => {
    let newLoginInfo = JSON.parse(JSON.stringify(loginInfo));
    newLoginInfo[key] = value;
    setLoginInfo(newLoginInfo);
  }

  //로그인 엔터
  const loginEnter = (key) => {
    if (key == 'Enter') {
      login();
    } else {
      return;
    }
  }

  //로그인
  const login = () => {
    fetch("/user/login.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(loginInfo),
    }).then((response) => response.json()).then((data) => {
      console.log("로그인 결과 : ", data);
      if (data.isSuccess == true) {       
        navigate('/');
      } else {
        alert(data.message);
      }
    }).catch((error) => {
      console.log('login() /user/login.json error : ', error);
    });
  };

  return (
    <div className="row login-wrap">
      <h1>시니어 스마트 케어 모니터링 플랫폼</h1>
      {location.pathname == '/Join' ? (<Join />) : (
        <div className="container row flex-center join-login">
          <div className="login-form">
            <div>
              <h3>로그인</h3>
              <div className="login-inner">
                <div className="content">
                  <i className="fa-solid fa-user"></i>
                  <input type="text" placeholder="아이디를 입력하세요"
                    value={loginInfo['user_id']}
                    onChange={(e) => { loginInfoChange('user_id', e.target.value) }}
                    onKeyUp={(e) => { loginEnter(e.key) }}
                  />
                </div>
                <div className="content">
                  <i className="fa-solid fa-lock"></i>
                  <input type="password" placeholder="비밀번호를 입력하세요"
                    value={loginInfo['user_password']}
                    onChange={(e) => { loginInfoChange('user_password', e.target.value) }}
                    onKeyUp={(e) => { loginEnter(e.key) }}
                  />
                </div>
              </div>
            </div>
            <div className="btn-wrap">
              <Button
                className={"btn-100 gray-btn"}
                btnName={"로그인"}
                onClick={login}
              />
              {/* <div className="flex-center btn-bottom">
                <Button
                  className={"join-btn"}
                  btnName={"회원가입"}
                  onClick={() => { navigate('/Join') }}
                />
              </div> */}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
