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(resp !== undefined){
                    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("아이디 찾기")
            setModalBody(IdFindForm)
            handleShow();
        }
    )
    const pwFindModal = () => {
        setModalTitle("비밀번호 찾기")
        setModalBody(PwFindForm)
        handleShow();
    }

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

    return (
        <>
            <div className="contents" id="contents">
                {/* <!-- 본문 --> */}
                <div className="Plogin">
                    <h1>로그인</h1>
                    <div className="login_box">
                        <fieldset>
                            <legend>로그인</legend>
                            <div className="input-group">
                                <span className="input-group-text"><img src="/assets/images/icon_id.png" /></span>
                                <input type="text" className="form-control shadow-none" title="아이디" placeholder="아이디" value={userInfo?.username}
                                 onChange={e => setUserInfo({ ...userInfo, username: e.target.value })} />
                            </div>
                            <div className="input-group mt-3">
                                <span className="input-group-text"><img src="/assets/images/icon_pw.png" /></span>
                                <input type="password" className="form-control shadow-none" title="비밀번호" placeholder="비밀번호"
                                       onChange={e => setUserInfo({ ...userInfo, password: e.target.value })} />
                            </div>
                            {/*<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={"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}>아이디 찾기</em>
                                    <em> | </em>
                                    <em className="clickable" onClick={pwFindModal}>비밀번호 찾기</em>
                                </Col>
                            </Row>
                            <button type="button" onClick={submitFormHandler} className="btn btn-22498E btn-lg">로그인</button>
                            <div className="line_t"></div>
                            <div className="line_b"></div>
                            <Link to={URL.JOIN} className="btn btn-outline-secondary btn-lg w-100">회원가입</Link>
                        </fieldset>
                    </div>
                </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;