import {React, useCallback, useEffect, useState} from "react";
import Modal from "react-bootstrap/Modal";
import * as EgovNet from "../../api/egovFetch";
import {VwDiv} from "./Vw.style";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";

const BookmarkModal = ({docCode, docPart, ymd}) => {
    const [modalTitle, setModalTitle] = useState();
    const [modalBody, setModalBody] = useState();
    const [docInfo, setDocInfo] = useState();

    const getModalContent = useCallback((selectedYmd) => {
        EgovNet.requestFetch(
            '/standardCode/getCodeDetailInfo.do',
            {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    docCode: docCode,
                    docPart: docPart,
                    ymd: selectedYmd===undefined?ymd:selectedYmd
                })
            },
            (resp) => {
                let bodyTag = []
                if(resp.result.document.length>0){
                    resp.result.document.forEach(function (item, index){
                        const isTitle = item.full_content.includes(item.group_title);
                        if(item.cont_label === docPart){
                            setModalTitle(item.group_title);
                        }
                        if(item.full_content.includes("<table")){
                            item.full_content = item.full_content.replace('<table ', '<table class="table table-bordered "')
                        }
                        bodyTag.push(
                            <VwDiv depth={item.cont_level} isTitle={isTitle} id={item.cont_type_cd} dangerouslySetInnerHTML={ {__html: item.full_content} }></VwDiv>
                        )
                    })
                }
                setModalBody(bodyTag);
            },
            (resp) => {
                console.log("err response : ", resp);
            }
        );
    })

    const getCodeInfo = useCallback(() => {
        console.groupCollapsed("EgovMain.getCodeInfo()");
        EgovNet.requestFetch(
            '/standardCode/getCodeInfo.do',
            {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    docCode: docCode
                })
            },
            (resp) => {
                const docInfo = resp.result.docInfo;
                // 헤더 연도 선택지 구성
                let headTag = [];
                if(docInfo.length>0){
                    let optionTag = [];
                    let activeIndex = 0;
                    let docTitle = "";
                    docInfo.forEach(function (item, index){
                        if(new Date(item.rvsn_ymd) <= new Date(ymd)){
                            activeIndex = index;
                            docTitle = item.doc_nm
                        }
                    })
                    docInfo.forEach(function (item, index){
                        let buttonClass = "btn btn-sm modalDocInfoBtn "
                        let pClass = "modalYearInfo ";
                        if(item.doc_er === 'E'){
                            buttonClass += "btn-success "
                        }else{
                            buttonClass += "btn-primary "
                        }
                        if(index === activeIndex){
                            pClass += "modalYearInfoActive"
                            buttonClass += "modalDocInfoActive"
                        }
                        optionTag.push(
                            <Col xs={"auto"}>
                                <input type="button"
                                       className={buttonClass}
                                       value={item.doc_er==='E'?'제':'개'}
                                       onClick={docInfoSelectorChange}
                                       data-ymd={item.rvsn_ymd}/>
                                <br/>
                                <p className={pClass}>{item.doc_yr}</p>
                            </Col>)
                    })
                    headTag.push(
                        <Row className="docInfoRow justify-content-start">
                            <Col xs={"auto"} className="docInfoTitle">{docCode} {docTitle}</Col>
                            {optionTag}
                        </Row>
                    )
                }else{
                    headTag.push(<div>검색된 결과가 없습니다.</div>); // 코드 목록 초기값
                }
                setDocInfo(headTag);
            }
        )
    })

    const docInfoSelectorChange = useCallback((el) => {
        setModalBody([<div>불러오는중</div>])
        const activeBtn = document.querySelector(".modalDocInfoActive")
        activeBtn.className = activeBtn.className.replace('modalDocInfoActive', '').trim();
        const activeP = document.querySelector(".modalYearInfoActive")
        activeP.className = activeP.className.replace('modalYearInfoActive', '').trim();
        const clickBtn = el.target;
        clickBtn.className += " modalDocInfoActive";
        clickBtn.parentElement.querySelector("p").className += " modalYearInfoActive"
        getModalContent(clickBtn.dataset.ymd);
    })

    useEffect(() => {
        getModalContent();
        getCodeInfo();
    }, []);

    return (
        <>
            <Modal.Header className="bookmarkModalHeader" closeButton>
                <Modal.Title>
                    {docInfo} {modalTitle}
                </Modal.Title>
            </Modal.Header>
            <Modal.Body>
                {modalBody}
            </Modal.Body>
        </>
    );
}
export default BookmarkModal