import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { Empty } from 'antd';

/* =====================================================
   🔧 通用初始化 Hook （核心）
===================================================== */
const useEchartInit = (theme?: string | object) => {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstance = useRef<echarts.ECharts | null>(null);

    // 初始化 ECharts 实例（只执行一次）
    useEffect(() => {
        if (!chartRef.current) return;
        const chart = echarts.init(chartRef.current, theme);
        chartInstance.current = chart;

        const handleResize = () => chart.resize();
        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
            chart.dispose();
            chartInstance.current = null;
        };
    }, [theme]);

    return { chartRef, chartInstance };
};

/* =====================================================
   🎨 默认颜色色板
===================================================== */
const DEFAULT_COLORS = [
    '#5470C6', '#91CC75', '#EE6666', '#FAC858',
    '#73C0DE', '#3BA272', '#FC8452', '#9A60B4', '#EA7CCC'
];

/* =====================================================
   📊 通用 Echarts 容器组件
===================================================== */
interface EchartsProps {
    option?: echarts.EChartsOption | null;
    style?: React.CSSProperties;
    theme?: string | object;
    loading?: boolean;
}

const Echarts: React.FC<EchartsProps> = ({ option, style = { width: '100%', height: '100%' }, theme, loading }) => {
    const { chartRef, chartInstance } = useEchartInit(theme);

    useEffect(() => {
        if (!chartInstance.current) return;
        if (!option) {
            chartInstance.current.clear();
            return;
        }

        loading ? chartInstance.current.showLoading() : chartInstance.current.hideLoading();
        chartInstance.current.setOption(option, true);
    }, [option, loading]);

    return <div ref={chartRef} style={style} />;
};

/* =====================================================
   📈 折线图 Line
===================================================== */
export interface LineData {
    legendName: string;
    [key: string]: any;
}

interface LineProps {
    data?: LineData[];
    title?: string;
    smooth?: boolean;
    areaStyle?: boolean;
    seriesFocus?: boolean;
    color?: string[];
    fontColor?: string;
    style?: React.CSSProperties;
    loading?: boolean;
}

const Line: React.FC<LineProps> = ({
    data = [],
    title,
    smooth = false,
    areaStyle = false,
    seriesFocus = false,
    color = DEFAULT_COLORS,
    fontColor,
    style = { width: '100%', height: 400 },
    loading = false
}) => {
    const { chartRef, chartInstance } = useEchartInit();

    useEffect(() => {
        if (!chartInstance.current) return;
        if (!data.length) {
            chartInstance.current.clear();
            return;
        }

        const textStyle = fontColor ? { color: fontColor } : {};
        const xData = Object.keys(data[0]).filter(k => k !== 'legendName');
        const seriesData = data.map((item, i) => ({
            name: item.legendName,
            type: 'line',
            data: xData.map(k => item[k]),
            smooth,
            areaStyle: areaStyle ? {} : undefined,
            emphasis: seriesFocus ? { focus: 'series' } : undefined
        }));

        const option: echarts.EChartsOption = {
            color,
            title: { text: title, left: 'center', textStyle },
            tooltip: { trigger: 'axis' },
            legend: { data: data.map(i => i.legendName), bottom: 0, textStyle },
            xAxis: { type: 'category', data: xData, boundaryGap: false },
            yAxis: { type: 'value' },
            grid: { left: 60, right: 40, bottom: 80 },
            series: seriesData as any
        };

        loading ? chartInstance.current.showLoading() : chartInstance.current.hideLoading();
        chartInstance.current.setOption(option, true);
    }, [data, title, smooth, areaStyle, color, fontColor, seriesFocus, loading]);

    return <div ref={chartRef} style={style} />;
};

/* =====================================================
   🥧 饼图 Pie
===================================================== */
interface PieProps {
    data?: { name: string; value: number }[];
    title?: string;
    color?: string[];
    style?: React.CSSProperties;
    loading?: boolean;
}

const Pie: React.FC<PieProps> = ({
    data = [],
    title,
    color = DEFAULT_COLORS,
    style = { width: '100%', height: 400 },
    loading = false
}) => {
    const { chartRef, chartInstance } = useEchartInit();

    useEffect(() => {
        if (!chartInstance.current) return;
        if (!data.length) {
            chartInstance.current.clear();
            return;
        }

        const option: echarts.EChartsOption = {
            color,
            title: { text: title, left: 'center' },
            tooltip: { trigger: 'item' },
            legend: { bottom: 0, left: 'center' },
            series: [
                {
                    type: 'pie',
                    radius: '60%',
                    data,
                    label: { formatter: '{b}: {d}%', color: '#333' },
                    emphasis: {
                        itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.3)' }
                    }
                }
            ]
        };

        loading ? chartInstance.current.showLoading() : chartInstance.current.hideLoading();
        chartInstance.current.setOption(option, true);
    }, [data, title, color, loading]);

    return <div ref={chartRef} style={style} />;
};

/* =====================================================
   📊 柱状图 Bar（支持横向）
===================================================== */
interface BarProps {
    /** 多组数据格式 */
    data?: Record<string, any>[];
    title?: string;
    color?: string[];
    horizontal?: boolean;
    style?: React.CSSProperties;
    loading?: boolean;
}

const Bar: React.FC<BarProps> = ({
    data = [],
    title,
    color = DEFAULT_COLORS,
    horizontal = false,
    style = { width: '100%', height: 400 },
    loading = false
}) => {
    const { chartRef, chartInstance } = useEchartInit();

    useEffect(() => {
        if (!chartInstance.current) return;
        if (!data.length) {
            chartInstance.current.clear();
            return;
        }

        // ✅ 自动识别维度
        const keys = Object.keys(data[0]);
        const categoryKey = keys[0]; // 默认第一列为类目轴
        const seriesKeys = keys.slice(1); // 其他列为系列名

        const categories = data.map(d => d[categoryKey]);

        const series = seriesKeys.map((key, idx) => ({
            name: key,
            type: 'bar',
            data: data.map(d => d[key]),
            barGap: 0,
            emphasis: { focus: 'series' },
            itemStyle: { borderRadius: 3 },
        }));

        const option: echarts.EChartsOption = {
            color,
            title: { text: title, left: 'center' },
            tooltip: { trigger: 'axis' },
            legend: { data: seriesKeys, bottom: 0 },
            grid: horizontal
                ? { left: 120, right: 50, top: 60, bottom: 60 }
                : { left: 60, right: 40, top: 60, bottom: 100 },
            xAxis: horizontal
                ? { type: 'value' }
                : {
                    type: 'category',
                    data: categories,
                    axisLabel: { interval: 0, rotate: 30 }
                },
            yAxis: horizontal
                ? { type: 'category', data: categories }
                : { type: 'value' },
            series: horizontal
                ? series.map(s => ({ ...s, label: { show: true, position: 'right' } })) as any
                : series.map(s => ({ ...s, label: { show: true, position: 'top' } })) as any
        };

        loading ? chartInstance.current.showLoading() : chartInstance.current.hideLoading();
        chartInstance.current.setOption(option, true);
    }, [data, title, color, horizontal, loading]);

    return <div ref={chartRef} style={style} />;
};

/* =====================================================
   导出 Hook
===================================================== */
const useEcharts = () => ({ Echarts, Line, Pie, Bar });
export default useEcharts;