import React, {useState, useEffect, useCallback, useRef} from 'react';
import {Link, useLocation, useParams} from 'react-router-dom';

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';
import {StandardCodeListModal, StandardCodeListModalTable} from './StandardCodeListModal'
import {AiFillFileMarkdown, AiFillStar} from "react-icons/ai";

function StandardCodeList(props) {
    const {listCode} = useParams();
    const [show, setShow] = useState(false);
    const [groupSeq, setgroupSeq] = useState();

    console.group("StandardCodeList");
    console.log("[Start] StandardCodeList ------------------------------");
    console.log("StandardCodeList [props] : ", props);
    console.log("listcode----------------------------" + listCode);

    const location = useLocation();
    console.log("StandardCodeList [location] : ", location);

    const category1Ref = useRef();
    const category2Ref = useRef();
    const category3Ref = useRef();
    const wrdRef = useRef();

    // eslint-disable-next-line no-unused-vars
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || {
        pageIndex: 1,
        tab: listCode?.substring(0, 2),
        category1: listCode?.substring(2, 4),
        category2: listCode?.substring(4, 6),
        searchWrd: ''
    });// 기존 조회에서 접근 했을 시 || 신규로 접근 했을 시
    const [masterBoard, setMasterBoard] = useState({});

    /* 검색기능 추가 변수*/
    const [listData, setlistData] = useState([]);
    const [filterData, setFilterData] = useState('');
    const [category1List, setCategory1List] = useState([]);
    const [category2List, setCategory2List] = useState([]);
    const [category3List, setCategory3List] = useState([]);
    const [resultCnt, setResultCnt] = useState(0);

    /* 탭 */
    const [activeTab, setActiveTab] = useState(10);
    const [subTabsVisible, setSubTabsVisible] = useState(false);

    function close() {
        setShow(false);
    }
    
    function showHandling(e) {
        const param = e.currentTarget.dataset;
        const groupSeq = param.groupSeq;
        console.log(groupSeq);
        EgovNet.requestFetch(
            '/standardCode/codeListModal.do',
            {
                method: "POST",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(
                    groupSeq
                )
            }, (resp) => {
                console.log(resp + "------------------------resp")
                const body = [];
                const head = [];
                if (resp.length > 0) {

                    resp.forEach(function (item, index) {
                        const formattedDate = item.aplcnBgngYmd.match(/\d{4}-\d{2}-\d{2}/)[0];
                        const url = "https://www.kcsc.re.kr/file/DownloadGrp/" + item.docFileGrpId;
                        body.push(
                            <tr>
                                <td>{formattedDate}</td>
                                <td><a href={url}><AiFillFileMarkdown/></a></td>
                                <td></td>
                            </tr>)
                    })
                    head.push(
                        <tr>
                            <td>년도</td>
                            <td>기준코드</td>
                            <td>신구건설기준비교</td>
                        </tr>
                    )
                }

                setgroupSeq(<StandardCodeListModalTable head={head} content={body}/>);
            }
        )
        setShow(true);

    }

    
    const handleTabClick = (tabName) => {
        setActiveTab(tabName);

        const updatedCondition = {
            ...searchCondition,
            tab: tabName,
            category1: '',
            category2: '',
            category3: '',
            searchWrd: '',
        };

        setSearchCondition(updatedCondition);
        retrieveList(updatedCondition);

        if ([40, 50, 60, 70, 80, 90].includes(tabName)) {
            setSubTabsVisible(true);
        } else {
            setSubTabsVisible(false);
        }
    };

    const retrieveList = useCallback((searchCondition) => {
        console.groupCollapsed("StandardCodeList.retrieveList()");

        const retrieveListURL = '/standardCode/selectStandardCodeList.do';
        const requestOptions = {
            method: "POST",
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify(searchCondition)
        }

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                setMasterBoard(resp.result.tnDocumentInfo);
                /*검색을 위한 리스트 state에 저장*/
                setlistData(resp.result.resultList);
                setCategory1List(resp.result.category1List);
                setCategory2List(resp.result.category2List);
                setCategory3List(resp.result.category3List);
                setResultCnt(resp.result.resultCnt);
                // 리스트 항목 구성
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        console.groupEnd("StandardCodeList.retrieveList()");
    }, []);

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

    console.log("------------------------------StandardCodeList [End]");
    console.groupEnd("StandardCodeList");
    return (
        <div className="StandardCodeList container">
            <div className="c_wrap codelistcontent">
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li><Link to='#'>건설기준코드</Link></li>
                        <li><Link to={URL.STANDARD_CODE_LIST}>건설기준코드 검색</Link></li>
                    </ul>
                </div>
                <div className="layout">
                    <div className="contents NOTICE_LIST listtablediv">
                        <div className="top_tit">
                            <h2 className="tit_1">건설기준코드 검색</h2>
                        </div>
                        <div className="condition">
                            <ul>
                                <li className="third_1 L">
                                    <div className={`tab ${activeTab === 10 ? 'active' : ''}`} onClick={() => handleTabClick(10)}>설계기준</div>
                                </li>
                                <li className="third_1 L">
                                    <div className={`tab ${activeTab === 20 ? 'active' : ''}`} onClick={() => handleTabClick(20)}>표준시방서</div>
                                </li>
                                <li className="third_1 L">
                                    <div className={`tab ${[40, 50, 60, 70, 80, 90].includes(activeTab) ? 'active' : ''}`} onClick={() => handleTabClick(40)}>전문시방서</div>
                                </li>
                                <li className="third_1 L">
                                    <label className="f_select" htmlFor="sel1">
                                        <select id="sel1" title="조건" value={searchCondition.category1} ref={category1Ref}
                                                onChange={e => {
                                                    const updatedCondition = {
                                                        ...searchCondition,
                                                        category1: e.target.value,
                                                        category2: '',
                                                        category3: '',
                                                        searchWrd: wrdRef.current.value,
                                                        tab: activeTab
                                                    };

                                                    setSearchCondition(updatedCondition);
                                                    retrieveList(updatedCondition);
                                                }}
                                        >
                                            <option value="">전체</option>
                                            {category1List.map(category => (
                                                <option key={category.groupSeq} value={category.groupFullCd.substring(2, 4)}>{category.groupNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                </li>
                                <li className="third_1 L">
                                    <label className="f_select w_306" htmlFor="sel1">
                                        <select id="sel2" title="조건" value={searchCondition.category2} ref={category2Ref}
                                                onChange={e => {
                                                    const updatedCondition = {
                                                        ...searchCondition,
                                                        category1: category1Ref.current.value,
                                                        category2: category2Ref.current.value,
                                                        category3: '',
                                                        searchWrd: wrdRef.current.value,
                                                        tab: activeTab
                                                    };

                                                    setSearchCondition(updatedCondition);
                                                    retrieveList(updatedCondition);
                                                }}
                                        >
                                            <option value="">전체</option>
                                            {category2List.map(category => (
                                                <option key={category.groupSeq} value={category.groupFullCd.substring(4, 6)}>{category.groupNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                </li>
                                <li className="third_1 L">
                                    <label className="f_select w_306" htmlFor="sel1">
                                        <select id="sel3" title="조건" value={searchCondition.category3} ref={category3Ref}
                                                onChange={e => {
                                                    const updatedCondition = {
                                                        ...searchCondition,
                                                        category1: category1Ref.current.value,
                                                        category2: category2Ref.current.value,
                                                        category3: category3Ref.current.value,
                                                        searchWrd: wrdRef.current.value,
                                                        tab: activeTab
                                                    };

                                                    setSearchCondition(updatedCondition);
                                                    retrieveList(updatedCondition);
                                                }}
                                        >
                                            <option value="">전체</option>
                                            {category3List.map(category => (
                                                <option key={category.groupSeq} value={category.groupFullCd.substring(6, 8)}>{category.groupNm}</option>
                                            ))}
                                        </select>
                                    </label>
                                </li>
                                <li className="third_1 L">
                                    <div className={`tab`}>통합 다운로드</div>
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}
                        {subTabsVisible && (
                            <div className="right_col">
                                <div className="mini_board">
                                    <ul>
                                        <div className={`tab ${activeTab === 40 ? 'active' : ''}`} onClick={() => handleTabClick(40)}>서울특별시</div>
                                        <div className={`tab ${activeTab === 50 ? 'active' : ''}`} onClick={() => handleTabClick(50)}>고속도로공사</div>
                                        <div className={`tab ${activeTab === 60 ? 'active' : ''}`} onClick={() => handleTabClick(60)}>한국농어촌공사</div>
                                        <div className={`tab ${activeTab === 70 ? 'active' : ''}`} onClick={() => handleTabClick(70)}>철도건설공사</div>
                                        <div className={`tab ${activeTab === 80 ? 'active' : ''}`} onClick={() => handleTabClick(80)}>LH한국토지주택공사</div>
                                        <div className={`tab ${activeTab === 90 ? 'active' : ''}`} onClick={() => handleTabClick(90)}>K-Water</div>
                                    </ul>
                                </div>
                            </div>
                        )}
                        <div><span>전체 {resultCnt} 건</span></div>
                        {/* <!-- 게시판목록 --> */}
                        <div className="board_list BRD002 code_list">
                            <div className="head">
                                <span>대분류</span>
                                <span>중분류</span>
                                <span>코드번호</span>
                                <span>코드명</span>
                                <span>개정이력</span>
                                <span>보기</span>
                                <span>다운로드</span>
                                <span>즐겨찾기</span>
                            </div>
                            <div className="result">

                                {/*검색기능 filterData가 없는경우 모든 데이터 출력*/}
                                {listData.filter(item => {
                                    if (item.groupNm.includes(filterData)) {
                                        return item
                                    }
                                    return null
                                }).map(item => {
                                    return (
                                        <div className="list_item List_Codes">
                                            <div className="mainCategory">{item.mainCategory}</div>
                                            <div className="middleCategory">{item.middleCategory}</div>
                                            <div className="kcscCd">{item.kcscCd}</div>
                                            <div className="groupNm">{item.groupNm}</div>
                                            <div className="Revisionhistory"><a className="vieweratag" onClick={showHandling} data-groupSeq={item.groupSeq}>개정이력</a></div>
                                            <div className="fille">{item.contentcount > 0 ? <a className="vieweratag" href={"/standardCode/viewer/" + item.kcscCd}>내용보기</a> : null}</div>
                                            <div className="viewer">{item.docFileGrpId == null ? null :
                                                <a href={"https://www.kcsc.re.kr/file/DownloadGrp/" + item.docFileGrpId}><AiFillFileMarkdown/></a>}</div>
                                            <div className="star"><AiFillStar/></div>
                                        </div>
                                    )
                                })}
                            </div>
                        </div>
                        {/* <!--// 게시판목록 --> */}


                        {/* <!-- Paging --> */}

                        {/* <!--/ Paging --> */}
                        <StandardCodeListModal size={"lg"} show={show} content={groupSeq} onClose={close} title={"개정이력"}/>


                        {/* <!--// 본문 --> */}
                    </div>
                </div>
            </div>
        </div>
    );
}


export default StandardCodeList;

