import React, {useState, useEffect, useRef} from 'react';
import {Link, useNavigate, useLocation, useParams} from 'react-router-dom';
import Modal from "react-bootstrap/Modal";

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';
import CODE from 'constants/code';

import {default as EgovLeftNav} from 'components/leftmenu/EgovLeftNavAdmin';
import EgovRadioButtonGroup from 'components/EgovRadioButtonGroup';
import {Form} from "react-bootstrap";


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

    const navigate = useNavigate();
    const location = useLocation();
    const checkRef = useRef([]);

    console.log("EgovAdminBoardEdit [location] : ", location);

    let item = null;
    item = props;
    console.log("@@@ item : " + JSON.stringify(item));

    const [modeInfo, setModeInfo] = useState(item != null ? {mode: props.mode} : {mode: CODE.MODE_CREATE});
    const [boardDetail, setBoardDetail] = useState({});
    console.log("@@@ mode : " + modeInfo.mode);

    useEffect(() => {
        initMode();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const initMode = () => {
        if (modeInfo.mode === CODE.MODE_MODIFY) {
            setBoardDetail(item);
        }
    }

    function editBoard(e) {
        e.preventDefault();
        e.stopPropagation();
        const form = e.target;
        const info = {
            bbsId: form.bbsId.value,
            bbsTitle: form.bbsTitle.value,
            bbsDesc: form.bbsDesc.value
        }
        if (modeInfo.mode === CODE.MODE_MODIFY) {
            info.bbsSeq = props.bbsSeq;
        }
        EgovNet.requestFetch(
            '/admin/boards/board-mgt',
            {
                method: "PUT",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(info)
            },
            (resp) => {
                if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                    alert("저장되었습니다.");
                    reloadFunction();
                } else if (Number(resp.resultCode) === Number(CODE.RCV_ERROR_AUTH)) {
                    console.log("토큰 갱신중.")
                } else {
                    alert(resp.result.resultMessage)
                }
            }
        )
    }

    function deleteBoard(bbs){
        if(window.confirm("삭제하시겠습니까?")) {
            EgovNet.requestFetch(
                '/admin/boards/board-mgt',
                {
                    method: "DELETE",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(bbs)
                },
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                        alert("삭제되었습니다.")
                        reloadFunction();
                    } else if (Number(resp.resultCode) === Number(CODE.RCV_ERROR_AUTH)) {
                        console.log("토큰 갱신중.")
                    } else {
                        alert(resp.result.resultMessage)
                    }
                }
            )
        }
    }

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

    return (
        <>
            {/* <!-- 본문 --> */}
            <Modal.Header closeButton>
                <Modal.Title>
                    {modeInfo.mode === CODE.MODE_CREATE && '게시판 생성'}
                    {modeInfo.mode === CODE.MODE_MODIFY && '게시판 수정'}
                </Modal.Title>
            </Modal.Header>

            <Modal.Body>
                <div className="board_view2">
                    <Form onSubmit={(e) => {editBoard(e)}} noValidate>
                        <dl>
                            <dt><label htmlFor="bbsId">게시판 ID</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="bbsId" placeholder="게시판 ID" required
                                              defaultValue={props?.bbsId} readOnly={props!==undefined}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">게시판명</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="bbsTitle" placeholder="게시판명" required
                                              defaultValue={props?.bbsTitle}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsDesc">게시판 소개</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full h_100" as="textarea" name="bbsDesc" placeholder="게시판 소개" required
                                              defaultValue={props?.bbsDesc}/>
                            </dd>
                        </dl>

                        {/* <!-- 버튼영역 --> */}
                        <div className="board_btn_area">
                            <div className="left_col btn1">
                                <button type="submit" className="btn btn_skyblue_h46 w_100">저장
                                </button>
                                {modeInfo.mode === CODE.MODE_MODIFY &&
                                <button type={"button"} className="btn btn_skyblue_h46 w_100" onClick={()=>{deleteBoard(props)}}>삭제</button>
                                }
                            </div>

                            <div className="right_col btn1">
                                <button type={"button"} className="btn btn_blue_h46 w_100" onClick={()=>{reloadFunction()}}>목록</button>
                            </div>
                        </div>
                        {/* <!--// 버튼영역 --> */}
                    </Form>
                </div>
            </Modal.Body>
        </>

    );
}

export default EgovAdminBoardEdit;