/**
 * KRA - Line Chart Component
 */
import React, { useMemo } from 'react';
import BaseChart from './BaseChart';
import type { EChartsOption } from 'echarts';

interface SeriesItem {
  name: string;
  data: number[];
}

interface LineChartProps {
  data?: { name: string; value: number }[];
  series?: SeriesItem[];
  xAxisData?: string[];
  title?: string;
  smooth?: boolean;
  areaStyle?: boolean;
  width?: string | number;
  height?: string | number;
  loading?: boolean;
}

const LineChart: React.FC<LineChartProps> = ({
  data,
  series,
  xAxisData,
  title,
  smooth = true,
  areaStyle = false,
  width,
  height = 300,
  loading,
}) => {
  const option: EChartsOption = useMemo(() => {
    // 支持两种数据格式
    let seriesData: any[];
    let xData: string[];

    if (series && series.length > 0) {
      // 使用 series 格式
      seriesData = series.map((s) => ({
        type: 'line',
        name: s.name,
        data: s.data,
        smooth,
        areaStyle: areaStyle ? {} : undefined,
      }));
      xData = xAxisData || [];
    } else if (data && data.length > 0) {
      // 使用 data 格式
      seriesData = [
        {
          type: 'line',
          data: data.map((item) => item.value),
          smooth,
          areaStyle: areaStyle ? {} : undefined,
        },
      ];
      xData = xAxisData || data.map((item) => item.name);
    } else {
      seriesData = [];
      xData = [];
    }

    return {
      title: title ? { text: title, left: 'center' } : undefined,
      tooltip: {
        trigger: 'axis',
      },
      legend: series && series.length > 1 ? { data: series.map((s) => s.name) } : undefined,
      xAxis: {
        type: 'category',
        data: xData,
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
      },
      series: seriesData,
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
    };
  }, [data, series, xAxisData, title, smooth, areaStyle]);

  return <BaseChart option={option} width={width} height={height} loading={loading} />;
};

export default LineChart;
