import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from 'recharts';
import type { TimeSeriesDataPoint } from '../types';

export interface ChartProps {
  /** Chart data points */
  data: TimeSeriesDataPoint[];
  /** Chart type */
  type?: 'line' | 'area' | 'bar';
  /** Height in pixels */
  height?: number;
  /** Color for the main data series */
  color?: string;
  /** Whether to show grid */
  showGrid?: boolean;
  /** Whether to show legend */
  showLegend?: boolean;
  /** Format function for X-axis labels */
  xAxisFormatter?: (value: Date) => string;
  /** Format function for Y-axis labels */
  yAxisFormatter?: (value: number) => string;
  /** Format function for tooltip values */
  tooltipFormatter?: (value: number) => string;
  /** Loading state */
  loading?: boolean;
  /** Custom CSS class */
  className?: string;
}

const defaultXAxisFormatter = (value: Date): string => {
  return new Date(value).toLocaleDateString();
};

const defaultYAxisFormatter = (value: number): string => {
  if (value >= 1000000) {
    return `${(value / 1000000).toFixed(1)}M`;
  }
  if (value >= 1000) {
    return `${(value / 1000).toFixed(1)}K`;
  }
  return value.toString();
};

export function Chart({
  data,
  type = 'line',
  height = 300,
  color = '#8884d8',
  showGrid = true,
  showLegend = false,
  xAxisFormatter = defaultXAxisFormatter,
  yAxisFormatter = defaultYAxisFormatter,
  tooltipFormatter,
  loading = false,
  className,
}: ChartProps) {
  if (loading) {
    return (
      <div
        className={className}
        style={{
          height,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#f5f5f5',
          borderRadius: '8px',
        }}
      >
        Loading...
      </div>
    );
  }

  const formattedData = data.map((point) => ({
    ...point,
    formattedTimestamp: xAxisFormatter(point.timestamp),
  }));

  const commonProps = {
    data: formattedData,
    margin: { top: 10, right: 30, left: 0, bottom: 0 },
  };

  const renderChart = () => {
    switch (type) {
      case 'area':
        return (
          <AreaChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="formattedTimestamp" />
            <YAxis tickFormatter={yAxisFormatter} />
            <Tooltip formatter={tooltipFormatter} />
            {showLegend && <Legend />}
            <Area
              type="monotone"
              dataKey="value"
              stroke={color}
              fill={color}
              fillOpacity={0.3}
            />
          </AreaChart>
        );
      case 'bar':
        return (
          <BarChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="formattedTimestamp" />
            <YAxis tickFormatter={yAxisFormatter} />
            <Tooltip formatter={tooltipFormatter} />
            {showLegend && <Legend />}
            <Bar dataKey="value" fill={color} />
          </BarChart>
        );
      default:
        return (
          <LineChart {...commonProps}>
            {showGrid && <CartesianGrid strokeDasharray="3 3" />}
            <XAxis dataKey="formattedTimestamp" />
            <YAxis tickFormatter={yAxisFormatter} />
            <Tooltip formatter={tooltipFormatter} />
            {showLegend && <Legend />}
            <Line
              type="monotone"
              dataKey="value"
              stroke={color}
              strokeWidth={2}
              dot={false}
            />
          </LineChart>
        );
    }
  };

  return (
    <div className={className} style={{ width: '100%', height }}>
      <ResponsiveContainer>{renderChart()}</ResponsiveContainer>
    </div>
  );
}
