import React, { useState, useEffect, useRef } from 'react';
import { Chart } from '@antv/g2';
import { useHomeStore } from './store';
import { Select } from 'antd';

import RagApplicationsTable from './components/RagApplicationsTable'
import RagApplicationsModel from './components/RagApplicationsModel'
import RagKnowledgModel from './components/RagKnowledgModel'
import { apis } from '@/apis';
import './style.scss'
const App: React.FC = () => {

    const {
        monthDay,
        topData,
        onlineUserData,
        conversationData,
        conversationDetailData,
        overviewTokenData,
        init,
        setMonthDay,
    } = useHomeStore();

    // 图表容器引用
    const allSessionsChartRef = useRef<HTMLDivElement>(null);
    const activeUsersChartRef = useRef<HTMLDivElement>(null);
    const avgInteractionsChartRef = useRef<HTMLDivElement>(null);
    const tokenSpeedChartRef = useRef<HTMLDivElement>(null);
    const [tenantDetail, setTenantDetail] = React.useState<any>({})
    const [percent, setPercent] = React.useState<any>(0)

    // 初始化图表的函数
    const initChart = (
        containerRef: React.RefObject<HTMLDivElement>,
        data: any[],
        title: string,
        color: string,
        tickInterval: number = 0
    ) => {
        if (!containerRef.current) return;

        const chart = new Chart({
            container: containerRef.current,
            autoFit: true,
            height: 250,
        });

        chart.data(data);

        // 面积图
        chart.area()
            .position(`${monthDay}*value`)
            .color(color)
            .style({ fillOpacity: 0.2 });

        // 折线图
        chart.line()
            .position(`${monthDay}*value`)
            .color(color)
            .size(2);

        chart.scale('value', {
            min: 0,
            tickInterval: tickInterval,
        });

        chart.axis(monthDay, {
            // title: false,
        });

        chart.render();

        // 返回销毁函数
        return () => chart.destroy();
    };

    // 初始化所有图表
    useEffect(() => {
        init()
    }, []);

    useEffect(() => {
        // 第二个图表 - 活跃用户数 (绿色)
        const cleanup2 = initChart(
            activeUsersChartRef,
            onlineUserData,
            '活跃用户数',
            '#52C41A',
            1
        );
        // 清理函数
        return () => {
            cleanup2?.();
        };
    }, [onlineUserData])
    useEffect(() => {
        // 第二个图表 - 全部会话数 (绿色)
        const cleanup1 = initChart(
            allSessionsChartRef,
            conversationData,
            '全部会话数',
            '#1890FF',
            0
        );
        // 清理函数
        return () => {
            cleanup1?.();
        };
    }, [conversationData])
    useEffect(() => {
        // 第三个图表 - 平均会话互动数 (绿色)
        const cleanup3 = initChart(
            avgInteractionsChartRef,
            conversationDetailData,
            '平均会话互动数',
            '#FA8C16',
            0
        );
        // 清理函数
        return () => {
            cleanup3?.();
        };
    }, [conversationDetailData])
    useEffect(() => {
        // 第四个图表 - Token输出速度 (红色)
        const cleanup4 = initChart(
            tokenSpeedChartRef,
            overviewTokenData,
            'Token输出速度',
            '#F5222D',
            0
        );
        // 清理函数
        return () => {
            cleanup4?.();
        };
    }, [overviewTokenData])


    const [visible, setVisible] = useState(false);
    const [visibleKnow, setVisibleKnow] = useState(false);

    return (
        <div className="flex flex-col space-y-4 mt-6 px-6">
            {/* 时间选择器 */}
            <div>
                <Select
                    defaultValue="day"
                    style={{ width: 120 }}
                    onChange={(e) => {
                        setMonthDay(e)
                        fetchOverviewData()
                    }}
                    options={[
                        { value: 'day', label: '日' },
                        { value: 'month', label: '月' }
                    ]}
                >
                </Select>
            </div>

            {/* 四个图表，两列布局 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 全部会话数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">全部会话数</div>
                    <div ref={allSessionsChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* 活跃用户数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">活跃用户数</div>
                    <div ref={activeUsersChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* 平均会话互动数图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">平均会话互动数</div>
                    <div ref={avgInteractionsChartRef} style={{ width: '100%', height: '250px' }} />
                </div>

                {/* Token输出速度图表 */}
                <div className="bg-white rounded-lg shadow-sm border p-4">
                    <div className="text-gray-700 font-medium mb-2">Token输出速度（token/秒）</div>
                    <div ref={tokenSpeedChartRef} style={{ width: '100%', height: '250px' }} />
                </div>
            </div>
            <RagApplicationsTable onOpenApp={() => {
                setVisible(true)
            }} onOpenKnow={() => {
                setVisibleKnow(true)
            }} />
            <RagApplicationsModel visible={visible} onCancel={() => {
                setVisible(false)
            }} />
            <RagKnowledgModel visible={visibleKnow} onCancel={() => {
                setVisibleKnow(false)
            }} />
        </div>
    );
};

export default App;