import React, {useState, useEffect, useRef, useCallback} 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);

    const [bbsTypeList, setBbsTypeList] = useState([]);
    const [roleList, setRoleList] = useState([]);

    const retrieveList = useCallback(() => {
        const retrieveListURL = '/admin/boards/get-option-list';

        const requestOptions = {
            method: "GET",
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify()
        }

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                setBbsTypeList(resp.result.bbsTypeList);
                setRoleList(resp.result.roleList);
                console.log("@@@ bbsTypeList : " + JSON.stringify(resp.result.bbsTypeList));
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    },[]);

    useEffect(() => {
        retrieveList();
        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,
            bbsType: form.bbsType.value,
            bbsAnsYn: bbsAnsYn,
            bbsReplYn: bbsReplYn,
            useYn: useYn,
            readRole: form.readRole.value,
            writeRole: form.writeRole.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");

    const [bbsAnsYn, setBbsAnsYn] = useState(props?.bbsAnsYn || "N");
    const [bbsReplYn, setBbsReplYn] = useState(props?.bbsReplYn || "N");
    const [useYn, setUseYn] = useState(props?.useYn || "N");

    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>
                        <dl>
                            <dt><label htmlFor="bbsTitle">게시판 타입</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Select id="select1" name="bbsType">
                                    <option value="">선택</option>
                                    {bbsTypeList.map((item) => (
                                        <option key={item.itemCd} value={item.itemCd} selected={props?.bbsType === item.itemCd}>{item.itemNm}</option>
                                    ))}
                                </Form.Select>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">답글 여부</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Check
                                    type="checkbox"
                                    id="bbsAnsYnCheckbox"
                                    label="사용"
                                    checked={bbsAnsYn === 'Y'}
                                    onChange={(e) => setBbsAnsYn(e.target.checked ? 'Y' : 'N')}
                                />
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">댓글 여부</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Check
                                    type="checkbox"
                                    id="bbsReplYnCheckbox"
                                    label="사용"
                                    checked={bbsReplYn === 'Y'}
                                    onChange={(e) => setBbsReplYn(e.target.checked ? 'Y' : 'N')}
                                />
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">사용 여부</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Check
                                    type="checkbox"
                                    id="useYnCheckbox"
                                    label="사용"
                                    checked={useYn === 'Y'}
                                    onChange={(e) => setUseYn(e.target.checked ? 'Y' : 'N')}
                                />
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">읽기 권한</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Select id="select1" name="readRole">
                                    <option value="">선택</option>
                                    {roleList.map((item) => (
                                        <option key={item.itemCd} value={item.grpOrder} selected={props?.readRole === item.grpOrder}>{item.itemNm}</option>
                                    ))}
                                </Form.Select>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="bbsTitle">쓰기 권한</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Select id="select1" name="writeRole">
                                    <option value="">선택</option>
                                    {roleList.map((item) => (
                                        <option key={item.itemCd} value={item.grpOrder} selected={props?.writeRole === item.grpOrder}>{item.itemNm}</option>
                                    ))}
                                </Form.Select>
                            </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;