import React, {useState, useEffect, useCallback, useRef, PureComponent} from 'react';
import { Link, useLocation } from 'react-router-dom';
import {BarChart, Bar, Rectangle, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer} from 'recharts';

import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

import {format, sub} from "date-fns";
import { ko } from 'date-fns/locale';

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

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

import { itemIdxByPage } from 'utils/calc';

function UserConnections(props) {
    // console.group("EgovAdminPrivacyList");
    // console.log("[Start] EgovAdminPrivacyList ------------------------------");
    // console.log("EgovAdminPrivacyList [props] : ", props);
    const nowDate = new Date();
    const oneMonthAgoDate = sub(nowDate, { months: 1 });
    const [start_date, setStartDate] = useState(oneMonthAgoDate);
    const [end_date, setEndDate] = useState(nowDate);           // new Date()

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

    // eslint-disable-next-line no-unused-vars
    const [searchCondition, setSearchCondition] = useState(location.state?.searchCondition || {start_date: format(start_date, "yyyy-MM-dd"), end_date: format(end_date, "yyyy-MM-dd")});
    const [chartData, setChartData] = useState([]);

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

    const retrieveList = useCallback((srchCnd) => {
        // console.groupCollapsed("EgovAdminUsageList.retrieveList()");
        const retrieveListURL = '/admin/logs/user';

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

        EgovNet.requestFetch(
            retrieveListURL,
            requestOptions,
            (resp) => {
                let mutListTag = [];

                const resultCnt = parseInt(resp.result.resultCnt);
                const currentPageNo = 1;            // resp.result.paginationInfo.currentPageNo;
                const pageSize = resultCnt;         // resp.result.paginationInfo.pageSize;

                // 리스트 항목 구성
                if (resultCnt === 0) {
                    mutListTag.push(<p className="no_data" key="0">데이터가 없습니다.</p>);
                } else {
                    resp.result.resultList.forEach(function (item, index) {
                        // if (index === 0) mutListTag = []; // 목록 초기화
                        const listIdx = itemIdxByPage(resultCnt, currentPageNo, pageSize, index);

                        mutListTag.push(
                            <div key={listIdx} className="list_item">
                                <div>{item[0]}</div>
                                <div style={{textAlign: 'right', paddingRight: '10px'}}>{item[1].toLocaleString()}</div>
                            </div>
                        );
                    });
                }
                setListTag(mutListTag);

                let chartDataArray = resp.result.resultList.map((item, index) => ({
                    logCnt: item[0],          // Assuming logCnt is the x-axis data
                    "접속수": item[1],     // Assuming menuTitle is the y-axis data
                }));
                setChartData(chartDataArray);
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
        // console.groupEnd("EgovAdminPrivacyList.retrieveList()");
    },[listTag]);

    const CustomTooltip = ({ active, payload, label }) => {
        if (active && payload && payload.length) {
            return (
                <div className="custom-tooltip">
                    <p className="intro">사용자 접속현황</p>
                    <p className="label">{`${label} : ${payload[0].value}`}</p>
                    {/*<p className="desc">Anything you want can be displayed here.</p>*/}
                </div>
            );
        }
        return null;
    };

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

    // console.log("------------------------------EgovAdminPrivacyList [End]");
    // console.groupEnd("EgovAdminPrivacyList");


    return (
        <div className="container">
            <div className="c_wrap">
                {/* <!-- Location --> */}
                <div className="location">
                    <ul>
                        <li><Link to={URL.MAIN} className="home">Home</Link></li>
                        <li><Link to={URL.ADMIN} >사이트관리</Link></li>
                        <li>로그현황</li>
                        <li>사용자 접속현황</li>
                    </ul>
                </div>
                {/* <!--// Location --> */}

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

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

                        <div className="top_tit">
                            <h1 className="tit_1">사용자 접속현황</h1>
                        </div>

                        {/* <!-- 검색조건 --> */}
                        <div className="condition">
                            <ul>
                                <li className="half L">
                                    <DatePicker
                                        dateFormat='yyyy-MM-dd'                     // 날짜 형태
                                        shouldCloseOnSelect                         // 날짜를 선택하면 datepicker가 자동으로 닫힘
                                        minDate={new Date('2017-01-01')}        // minDate 이전 날짜 선택 불가
                                        maxDate={new Date()}                        // maxDate 이후 날짜 선택 불가
                                        selected={start_date}
                                        locale={ko}
                                        className="f_input1 al_c"
                                        selectsStart
                                        startDate={start_date}
                                        endDate={end_date}
                                        onChange={(date) => {
                                            setStartDate(date);
                                            setSearchCondition({
                                                start_date: format(date, "yyyy-MM-dd"),
                                                end_date: format(end_date, "yyyy-MM-dd")
                                            });
                                        }}
                                    /> -
                                </li>
                                <li className="half R">
                                    <DatePicker
                                        dateFormat='yyyy-MM-dd'                     // 날짜 형태
                                        shouldCloseOnSelect                         // 날짜를 선택하면 datepicker가 자동으로 닫힘
                                        minDate={new Date('2017-01-01')}        // minDate 이전 날짜 선택 불가
                                        maxDate={new Date()}                        // maxDate 이후 날짜 선택 불가
                                        selected={end_date}
                                        locale={ko}
                                        className="f_input1 al_c"
                                        selectsEnd
                                        startDate={start_date}
                                        endDate={end_date}
                                        onChange={(date) => {
                                            setEndDate(date);
                                            setSearchCondition({
                                                start_date: format(start_date, "yyyy-MM-dd"),
                                                end_date: format(date, "yyyy-MM-dd")
                                            });
                                        }}
                                    />
                                </li>
                            </ul>
                        </div>
                        {/* <!--// 검색조건 --> */}

                        {/* <!-- 목록 --> */}
                        <div className="logs_list row">
                            <div className="col-sm-4 pe-0">
                                <div className="board_list BRD010">
                                    <div className="head">
                                        <span>접속일자</span>
                                        <span>접속횟수</span>
                                    </div>
                                    <div className="result overflow-auto">
                                        {listTag}
                                    </div>
                                </div>
                            </div>
                            <div className="col-sm-8 ps-0">
                                <ResponsiveContainer width="100%" height={477}>
                                    <BarChart data={chartData} layout="vertical"
                                              height={477}
                                              margin={{
                                                  top: 0,
                                                  right: 0,
                                                  left: 20,
                                                  bottom: 0,
                                              }}
                                    >
                                        <CartesianGrid strokeDasharray="3 3" />
                                        <XAxis type="number" />
                                        <YAxis type="category" dataKey="logCnt" tick={{ fontSize: 10, whiteSpace: 'nowrap' }} />
                                        <Tooltip content={<CustomTooltip/>} />
                                        <Legend />
                                        <Bar dataKey="접속수" fill="#87CEFA" activeBar={<Rectangle fill="gold" stroke="purple" />} />
                                    </BarChart>
                                </ResponsiveContainer>
                            </div>
                        </div>
                        {/* <!--// 목록 --> */}

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

export default UserConnections;