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 Switch from '@mui/material/Switch';

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

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

import { itemIdxByPage } from 'utils/calc';
import EgovPaging from 'components/EgovPaging';


function ApiKeys(props) {
    // console.group("EgovAdminPrivacyList");
    // console.log("[Start] EgovAdminPrivacyList ------------------------------");
    // console.log("EgovAdminPrivacyList [props] : ", props);
    const location = useLocation();
    // console.log("EgovAdminPrivacyList [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 [chartData, setChartData] = useState([]);
    const [user_id, setuser_id] = useState([]);

    const [listTag, setListTag] = useState([]);
    // const label = { inputProps: { 'aria-label': '사용여부' } };

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

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

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

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

                const resultCnt = parseInt(resp.result.resultCnt);
                const currentPageNo = resp.result.paginationInfo.pageIndex;
                const pageSize = resp.result.paginationInfo.rowCnt;

                const startIndex = (currentPageNo - 1) * pageSize;
                const endIndex = Math.min(startIndex + pageSize, resultCnt);

                // 리스트 항목 구성
                for (let index = startIndex; index < endIndex; index++) {
                    const listIdx = itemIdxByPage(resultCnt, currentPageNo, 0, index);          // pageSize 로 넣으면 listIdx값이 2배씩 줄어서 0으로 수정
                    const item = resp.result.resultList[index];

                    mutListTag.push(
                        <div key={listIdx} className="list_item">
                            <div>{item.userId}</div>
                            <div style={{ cursor: 'pointer' }}  onClick={() => handleApiKeyChart(item)}>{item.apiKey}</div>
                            <div>{item.startDt} ~ {item.endDt}</div>
                            <div>{item.idntyYn === 'Y' ? <Switch defaultChecked onChange={() => handleSwitchToggle(item)} /> : <Switch onChange={() => handleSwitchToggle(item)} />}</div>
                        </div>
                    );
                }
                setListTag(mutListTag);
            },
            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">API 요청 [{user_id}]</p>
                    <p className="label">{`${label} : ${payload[0].value}`}회</p>
                </div>
            );
        }
        return null;
    };

    const handleSwitchToggle = async (item) => {
        try {
            const updateApiEndpoint = '/admin/standards/apiupdate';
            const requestOptions = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(item),
            };

            const response = await EgovNet.requestFetch(updateApiEndpoint, requestOptions);
            const data = await response.json();

            if (response.ok) {
                console.log('Data updated successfully:', data);
                return { success: true, data };
            } else {
                console.error('Failed to update data:', data);
                return { success: false, error: data };
            }
        } catch (error) {
            console.error('Error during data update:', error);
            return { success: false, error };
        }
    };

    const handleApiKeyChart = (item) => {
        try {
            const updateApiEndpoint = '/admin/standards/apiDailyChart';
            const requestOptions = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(item),
            };

            EgovNet.requestFetch(
                updateApiEndpoint,
                requestOptions,
                (resp) => {
                    let chartDataArray = resp.result.resultList.map((item, index) => ({
                        logdt: item[0],             // Assuming logCnt is the x-axis data
                        "API 요청수": item[1],         // Assuming menuTitle is the y-axis data
                    }));
                    setChartData(chartDataArray);
                    // item.userId 값 넣기
                    console.log(`User ID: ${item.userId}`);
                    setuser_id(item.userId);
                },
                function (resp) {
                    console.log("err response : ", resp);
                }
            );
        } catch (error) {
            console.error('Error during data update:', error);
            return { success: false, error };
        }
    };

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

    // 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>API KEY 관리</li>
                     </ul>
                 </div>
                {/* <!--// Location --> */}

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

                    <div className="contents " id="contents">
                        {/* <!-- 본문 --> */}
                        <div className="top_tit">
                            <h1 className="tit_1">API KEY 관리</h1>
                        </div>

                        {/* <!-- 목록 --> */}
                        <div className="board_list BRD012">
                            <div className="head">
                                <span>사용자</span>
                                <span>발급키</span>
                                <span>승인기간</span>
                                <span>승인여부</span>
                            </div>
                            <div className="result">
                                {listTag}
                            </div>
                        </div>
                        {/* <!--// 목록 -->*/}

                        <div className="board_bot mt-1">
                            {/* <!-- Paging --> */}
                            <EgovPaging pagination={paginationInfo} moveToPage={passedPage => {
                                retrieveList({ ...searchCondition, pageIndex: passedPage })         //, searchCnd: cndRef.current.value, searchWrd: wrdRef.current.value
                            }} />
                            {/* <!--/ Paging --> */}
                        </div>
                        <div className="pt-2">
                            <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="logdt" tick={{ fontSize: 10, whiteSpace: 'nowrap' }} />
                                    <Tooltip content={<CustomTooltip/>} />
                                    <Legend />
                                    <Bar dataKey="API 요청수" fill="#87CEFA" activeBar={<Rectangle fill="gold" stroke="purple" />} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                        {/* <!--// 본문 -->*/}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default ApiKeys;