import React, { useMemo } from 'react';
import { BaseChart, BaseChartProps } from './BaseChart';
import type { TouchEvent, LegendConfig, XAxisConfig, YAxisConfig } from '../lib/charts/index';

/**
 * 条形图类型（横向柱状图）
 */
export type BarType = 'group' | 'stack';

/**
 * BarChart 组件的 Props 接口
 */
export interface BarChartProps extends Omit<BaseChartProps, 'type'> {
  /** 是否显示数据标签 */
  dataLabel?: boolean;
  /** 条形图类型 */
  barType?: BarType;
  /** X 轴配置 */
  xAxis?: XAxisConfig;
  /** Y 轴配置 */
  yAxis?: YAxisConfig;
  /** 图例是否显示 */
  legend?: boolean;
  /** 字体大小 */
  fontSize?: number;
  /** 背景颜色 */
  background?: string;
  /** 是否开启动画 */
  animation?: boolean;
  /** tooltip 格式化函数 */
  tooltipFormatter?: (item: any, category: string) => string;
}

/**
 * BarChart 横向柱状图组件
 *
 * 用于显示分类数据的横向柱状图，支持分组和堆叠模式
 * 与 ColumnChart 的区别在于坐标轴交换，类别在 Y 轴，数值在 X 轴
 */
export const BarChart: React.FC<BarChartProps> = (props) => {
  const {
    dataLabel = true,
    barType = 'group',
    xAxis,
    yAxis,
    legend = true,
    fontSize = 11,
    background = '#FFFFFF',
    animation = true,
    tooltipFormatter,
    categories = [],
    series = [],
    config = {},
    ...baseProps
  } = props;

  const chartRef = React.useRef<any>(null);

  /**
   * 默认配置
   */
  const defaultConfig = useMemo(() => {
    const legendConfig: LegendConfig = legend ? { show: true } : { show: false };
    return {
      legend: legendConfig,
      fontSize,
      background,
      animation,
      dataLabel,
      xAxis: xAxis ?? { disableGrid: true },
      yAxis: yAxis ?? {},
      extra: {
        bar: {
          type: barType,
          width: barType === 'group'
            ? (baseProps.height ? baseProps.height * 0.45 / (categories.length || 1) : 20)
            : undefined
        }
      }
    };
  }, [legend, fontSize, background, animation, dataLabel, xAxis, yAxis, barType, categories.length, baseProps.height]);

  /**
   * tooltip 事件处理
   */
  const handleTouchStart = (e: TouchEvent) => {
    if (chartRef.current && tooltipFormatter) {
      chartRef.current.showToolTip(e, {
        formatter: tooltipFormatter
      });
    } else if (chartRef.current) {
      chartRef.current.showToolTip(e, {
        formatter: (item: any, category: string) => {
          return category + ' ' + item.name + ':' + item.data;
        }
      });
    }
    baseProps.onTouchStart?.(e);
  };

  return (
    <BaseChart
      {...baseProps}
      categories={categories}
      series={series}
      type="bar"
      config={{ ...defaultConfig, ...config }}
      onTouchStart={handleTouchStart}
    />
  );
};

export default BarChart;
