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 AboutSiteModal({props, reloadFunction}) {
    console.group("AboutSiteModal");
    console.log("[Start] AboutSiteModal ------------------------------");
    console.log("AboutSiteModal [props] : ", props);

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

    console.log("AboutSiteModal [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("------------------------------AboutSiteModal [End]");
    console.groupEnd("AboutSiteModal");

    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">사이트명</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="bbsId" placeholder="사이트명" required
                                              defaultValue={props?.siteTitle} readOnly={props!==undefined}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">URL</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="bbsTitle" placeholder="URL" required
                                              defaultValue={props?.siteUrl}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsDesc">배너이미지</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full" type="text" name="bbsDesc" placeholder="배너이미지" required
                                              defaultValue={props?.fileGrpId}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsDesc">정렬순서</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full" type="text" name="bbsDesc" placeholder="정렬순서" required
                                              defaultValue={props?.siteOrder}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsDesc">사용여부</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full" type="text" name="bbsDesc" placeholder="사용여부" required
                                              defaultValue={props?.useYn}/>
                            </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 AboutSiteModal;