import React, {useState, useEffect, useRef, useCallback} from 'react';
import {Link, useLocation, useNavigate} from 'react-router-dom';
import * as EgovNet from 'api/egovFetch';
import {parseJwt} from "../../utils/parseJwt";

import URL from 'constants/url';
import CODE from 'constants/code';
import Form from "react-bootstrap/Form";
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Modal from "react-bootstrap/Modal";

import { getLocalItem, setLocalItem, setSessionItem } from 'utils/storage';
import IdFindForm from "./IdFindForm";
import PwFindForm from "./PwFindForm";

function EgovLoginContent(props) {
    console.group("EgovLoginContent");
    console.log("[Start] EgovLoginContent ------------------------------");
    console.log("EgovLoginContent [props] : ", props);

    const navigate = useNavigate();
    const location = useLocation();
    console.log("EgovLoginContent [location] : ", location);

    const [userInfo, setUserInfo] = useState({ username: '', password: 'default', email: '', userSe: 'ACC_TP02'});
    // eslint-disable-next-line no-unused-vars

    const [saveIDFlag, setSaveIDFlag] = useState(false);

    const [findModalState, setFindModalState] = useState(false);
    const [modalTitle, setModalTitle] = useState();
    const [modalBody, setModalBody] = useState();
    const handleClose = () => setFindModalState(false);
    const handleShow = () => setFindModalState(true);

    const checkRef = useRef();

    const KEY_ID = "KEY_ID";
    const KEY_SAVE_ID_FLAG = "KEY_SAVE_ID_FLAG";

    const handleSaveIDFlag = () => {
        setLocalItem(KEY_SAVE_ID_FLAG, !saveIDFlag)
        setSaveIDFlag(!saveIDFlag);
    };

    useEffect(() => {
        let idFlag = getLocalItem(KEY_SAVE_ID_FLAG);
        if (idFlag === null) {
            setSaveIDFlag(false);
            // eslint-disable-next-line react-hooks/exhaustive-deps
            idFlag = false;
        } else {
            setSaveIDFlag(idFlag);
        }

        if (idFlag === false) {
            setLocalItem(KEY_ID, "");
        } else {
        }
    }, []);

    useEffect(() => {
        let data = getLocalItem(KEY_ID);
        if (data !== null) {
            setUserInfo({ username: data, password: 'default', email: '', userSe: 'ACC_TP02' });
        }
    }, []);

    const submitFormHandler = (e) => {
        console.log("EgovLoginContent submitFormHandler()");

        const loginUrl = "/auth/login"
        const requestOptions = {
            method: "POST",
            headers: {
                'Content-type': 'application/json'
            },
            body: JSON.stringify(userInfo)
        }

        EgovNet.requestFetch(loginUrl,
            requestOptions,
            (resp) => {
                if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                    let accessToken = resp?.accessToken || null;
                    let resultVO = parseJwt(accessToken);
                    let refreshToken = resp?.refreshToken || null;

                    // setSessionItem('accessToken', accessToken);
                    setLocalItem('accessToken', accessToken);
                    setLocalItem('refreshToken', refreshToken);
                    // setSessionItem('loginUser', resultVO);
                    props.onChangeLogin(resultVO);
                    if (saveIDFlag) {
                        setLocalItem(KEY_ID, resultVO?.id);
                    }
                    navigate(URL.MAIN);
                    // PC와 Mobile 열린메뉴 닫기
                    document.querySelector('.all_menu.WEB').classList.add('closed');
                    document.querySelector('.btnAllMenu').classList.remove('active');
                    document.querySelector('.btnAllMenu').title = '전체메뉴 닫힘';
                    document.querySelector('.all_menu.Mobile').classList.add('closed');
                } else {
                    alert(resp.resultMessage)
                }
            })
    }

    const idFindModal = useCallback(
        ()=> {
            setModalTitle("ID 찾기")
            setModalBody(IdFindForm)
            handleShow();
        }
    )
    const pwFindModal = () => {
        setModalTitle("PW 찾기")
        setModalBody(PwFindForm)
        handleShow();
    }

    console.log("------------------------------EgovLoginContent [End]");
    console.groupEnd("EgovLoginContent");

    return (
        <>
            <div className="contents" id="contents">
                {/* <!-- 본문 --> */}
                <div className="Plogin">
                    <h1>로그인</h1>
                    <p className="txt">전자정부표준프레임워크 경량환경 홈페이지 로그인 페이지입니다.<br />로그인을 하시면 모든 서비스를 제한없이 이용하실 수 있습니다.</p>

                    <div className="login_box">
                        <fieldset>
                            <legend>로그인</legend>
                            <span className="group">
                                    <input type="text" name="" title="아이디" placeholder="아이디" value={userInfo?.username}
                                           onChange={e => setUserInfo({ ...userInfo, username: e.target.value })} />
                                    <input type="password" name="" title="비밀번호" placeholder="비밀번호"
                                           onChange={e => setUserInfo({ ...userInfo, password: e.target.value })} />
                                </span>
                            <Row className="chk justify-content-between">
                                <Col xs={3}>
                                    <Form.Check inline label={"ID 저장"} id={"saveid"} name={""} checked={saveIDFlag} onChange={handleSaveIDFlag}/>

                                    {/*<label className="f_chk" htmlFor="saveid" ref={checkRef}>
                                        <input type="checkbox" name="" id="saveid" onChange={handleSaveIDFlag} checked={saveIDFlag}/> <em>ID저장</em>
                                    </label>*/}
                                </Col>
                                <Col xs={"auto"}>
                                    <em className="clickable" onClick={idFindModal}>ID 찾기</em>
                                    <em className="clickable" onClick={pwFindModal}>PW 찾기</em>
                                    <Link to={URL.JOIN}><em>회원가입</em></Link>
                                </Col>
                            </Row>
                            <button type="button" onClick={submitFormHandler}><span>LOGIN</span></button>
                        </fieldset>
                    </div>

                    <ul className="list">
                        <li>비밀번호는 6~12자의 영문 대/소문자, 숫자, 특수문자를 혼합해서 사용하실 수 있습니다.</li>
                        <li>쉬운 비밀번호나 자주 쓰는 사이트의 비밀번호가 같을 경우, 도용되기 쉬우므로 주기적으로
                            변경하셔서 사용하는 것이 좋습니다.</li>
                    </ul>
                </div>
            </div>
            <Modal show={findModalState} onHide={handleClose}>
                <Modal.Header closeButton>
                    <Modal.Title>{modalTitle}</Modal.Title>
                </Modal.Header>
                <Modal.Body>{modalBody}</Modal.Body>
            </Modal>
        </>
    );
}

export default EgovLoginContent;