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

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';

import { default as EgovLeftNav } from 'components/leftmenu/EgovLeftNavAdmin';
import EgovPaging from 'components/EgovPaging';

import { itemIdxByPage } from 'utils/calc';
import CODE from "../../../constants/code";
import AboutSiteModal from "../config/aboutSiteMgt/AboutSiteModal";
import AdminPostMgtEdit from "./AdminPostMgtEdit";
import Modal from "react-bootstrap/Modal";
import {format} from "date-fns";
import {Form} from "react-bootstrap";

function AdminPostMgtList(props) {
    console.group("EgovAdminPostList");
    console.log("[Start] EgovAdminPostList ------------------------------");
    console.log("EgovAdminPostList [props] : ", props);

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

    // eslint-disable-next-line no-unused-vars
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || { pageIndex: 1, searchCnd: '0', searchWrd: '' });// 기존 조회에서 접근 했을 시 || 신규로 접근 했을 시
    const [paginationInfo, setPaginationInfo] = useState({});

    const cndRef = useRef();
    const wrdRef = useRef();

    const [listTag, setListTag] = useState([]);
    const [categoryList, setCategoryList] = useState([]);

    const [show, setShow] = useState(false);
    const [modalBody, setModalBody] = useState();
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    const retrieveList = useCallback(() => {
        handleClose();
        console.groupCollapsed("EgovAdminPostList.retrieveList()");

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

        EgovNet.requestFetch(retrieveListURL,
            requestOptions,
            (resp) => {
                setPaginationInfo(resp.result.paginationInfo);
                setCategoryList(resp.result.categoryList);

                let mutListTag = [];
                listTag.push(<p className="no_data" key="0">검색된 결과가 없습니다.</p>); // 게시판 목록 초기값

                // 리스트 항목 구성
                resp.result.postList.forEach(function (item, index) {
                    if (index === 0) mutListTag = []; // 목록 초기화
                    const finalModifiedDate = item.lastChgDt ? item.lastChgDt : item.frstCrtDt;
                    const formattedDate = finalModifiedDate ? format(finalModifiedDate, "yyyy-MM-dd HH:mm") : "";

                    mutListTag.push(
                        <div className="list_item">
                            <div></div>
                            <div>{item.bbsContTitle}</div>
                            <div>{item.frstCrtId}</div>
                            <div>{formattedDate}</div>
                            <div>{item.bbsReadCnt}</div>
                            <div>{item.fileGrpId}</div>
                            <div><button className={"btn btn_blue_h31 px-1"} onClick={()=>{editPost(item)}}>수정</button></div>
                        </div>
                    );
                });
                
                setListTag(mutListTag);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        console.groupEnd("EgovAdminPostList.retrieveList()");
    },[listTag, searchCondition]);

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

    const handleSelectChange = (e) => {

    }

    function editPost(item){
        handleShow();
        if(item != undefined) {
            item.mode = CODE.MODE_MODIFY;
        }
        setModalBody(<AdminPostMgtEdit props={item} reloadFunction={retrieveList}/>)
    }

    console.log("------------------------------EgovAdminPostList [End]");
    console.groupEnd("EgovAdminPostList");
    return (
        <div className="container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li>사이트관리</li>
                        <li>게시판현황</li>
                        <li>게시물 관리</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

                <div className="layout">
                    {/* <!-- Navigation --> */}
                    <EgovLeftNav></EgovLeftNav>
                    {/* <!--// Navigation --> */}

                    <div className="contents BOARD_CREATE_LIST" id="contents">
                        {/* <!-- 본문 --> */}

                        <div className="top_tit">
                            <h1 className="tit_1">게시물 관리</h1>
                        </div>

                        {/* <!-- 검색조건 --> */}
                        <div className="condition">
                            <ul>
                                <li className="third_1 L">
                                    <span className="lb">검색유형선택</span>
                                    <label className="f_select" htmlFor="searchCnd">
                                        <Form.Select id="select1" name="bbsId" onChange={handleSelectChange}>
                                            <option value="">선택</option>
                                            {categoryList.map((item) => (
                                                <option key={item.bbsSeq} value={item.bbsId} selected={props?.bbsId === item.bbsId}>{item.bbsTitle}</option>
                                            ))}
                                        </Form.Select>
                                    </label>
                                </li>
                                <li className="third_2 R">
                                    <span className="lb">검색어</span>
                                    <span className="f_search w_400">
                                        <input type="text" name="" defaultValue={searchCondition && searchCondition.searchWrd} placeholder="" ref={wrdRef}
                                            onChange={e => {
                                                wrdRef.current.value = e.target.value;
                                            }}
                                        />
                                        <button type="button"
                                            onClick={() => {
                                                retrieveList({ ...searchCondition, pageIndex: 1, searchCnd: cndRef.current.value, searchWrd: wrdRef.current.value });
                                            }}>조회</button>
                                    </span>
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}

                        {/* <!-- 게시판목록 --> */}
                        <div className="board_list BRD006">
                            <div className="head">
                                <span></span>
                                <span>제목</span>
                                <span>작성자</span>
                                <span>최종수정일</span>
                                <span>조회수</span>
                                <span>파일</span>
                                <span><button className={"btn btn_blue_h31 px-1"} onClick={()=>{editPost(undefined)}}>추가</button></span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>
                        {/* <!--// 게시판목록 --> */}

                        <div className="board_bot">
                            {/* <!-- Paging --> */}
                            <EgovPaging pagination={paginationInfo} moveToPage={passedPage => {
                                retrieveList({ ...searchCondition, pageIndex: passedPage, searchCnd: cndRef.current.value, searchWrd: wrdRef.current.value })
                            }} />
                            {/* <!--/ Paging --> */}
                        </div>

                        {/* <!--// 본문 --> */}
                    </div>
                </div>
            </div>
            <Modal show={show} onHide={handleClose} keyboard={false}>
                {modalBody}
            </Modal>
        </div>








    );
}

export default AdminPostMgtList;