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

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

    console.log("AdminPostMgtEdit [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 editPartnerSite(e) {
        e.preventDefault();
        e.stopPropagation();
        const form = e.target;
        const info = {
            siteTitle: form.siteTitle.value,
            siteUrl: form.siteUrl.value,
            fileGrpId: form.fileGrpId.value,
            siteOrder: form.siteOrder.value,
            useYn: form.useYn.value
        }
        if (modeInfo.mode === CODE.MODE_MODIFY) {
            info.siteSeq = props.siteSeq;
        }
        EgovNet.requestFetch(
            '/admin/config/partner-site-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 deletePartnerSite(partnerSite){
        if(window.confirm("삭제하시겠습니까?")) {
            EgovNet.requestFetch(
                '/admin/config/partner-site-mgt',
                {
                    method: "DELETE",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(partnerSite)
                },
                (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("------------------------------AdminPostMgtEdit [End]");
    console.groupEnd("AdminPostMgtEdit");

    const [defaultFixedYn, setDefaultFixedYn] = useState(props?.fixedYn || "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) => {editPartnerSite(e)}} noValidate>
                        <dl>
                            <dt><label htmlFor="siteTitle">상단고정</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Check
                                    type="checkbox"
                                    id="siteTitleCheckbox"
                                    label="상단고정"
                                    checked={defaultFixedYn === 'Y'}
                                    onChange={(e) => setDefaultFixedYn(e.target.checked ? 'Y' : 'N')}
                                />
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="siteTitle">비밀글</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="siteTitle" placeholder="비밀글" required
                                              defaultValue={props?.siteTitle} readOnly={props!==undefined}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="siteTitle">제목</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="siteTitle" placeholder="제목" required
                                              defaultValue={props?.siteTitle} readOnly={props!==undefined}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="siteUrl">파일</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="siteUrl" placeholder="파일" required
                                              defaultValue={props?.siteUrl}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="fileGrpId">내용</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full" type="text" name="fileGrpId" placeholder="내용" required
                                              defaultValue={props?.fileGrpId}/>
                            </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={()=>{deletePartnerSite(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 AdminPostMgtEdit;