/**
 * KRA - Base Chart Component
 * ECharts wrapper with responsive sizing
 */
import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

interface BaseChartProps {
  option: EChartsOption;
  width?: string | number;
  height?: string | number;
  autoResize?: boolean;
  theme?: string | object;
  loading?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

const BaseChart: React.FC<BaseChartProps> = ({
  option,
  width = '100%',
  height = 300,
  autoResize = true,
  theme,
  loading = false,
  className,
  style,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  // Initialize chart
  useEffect(() => {
    if (!chartRef.current) return;

    chartInstance.current = echarts.init(chartRef.current, theme);

    return () => {
      chartInstance.current?.dispose();
    };
  }, [theme]);

  // Update option
  useEffect(() => {
    if (!chartInstance.current) return;
    chartInstance.current.setOption(option, true);
  }, [option]);

  // Handle loading state
  useEffect(() => {
    if (!chartInstance.current) return;
    if (loading) {
      chartInstance.current.showLoading();
    } else {
      chartInstance.current.hideLoading();
    }
  }, [loading]);

  // Handle resize
  useEffect(() => {
    if (!autoResize || !chartInstance.current) return;

    const handleResize = () => {
      chartInstance.current?.resize();
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [autoResize]);

  return (
    <div
      ref={chartRef}
      className={className}
      style={{
        width: typeof width === 'number' ? `${width}px` : width,
        height: typeof height === 'number' ? `${height}px` : height,
        ...style,
      }}
    />
  );
};

export default BaseChart;
