import { useMemo } from 'react';
import { Chart, ChartProps } from './Chart';

export interface BarChartData {
  label: string;
  value: number;
}

export interface BarChartProps extends Omit<ChartProps, 'children'> {
  data: BarChartData[];
  xAxisLabel?: string;
  yAxisLabel?: string;
  color?: string;
  showGrid?: boolean;
  showValues?: boolean;
}

/**
 * Composant BarChart pour visualisation de données en barres.
 */
export function BarChart({
  data,
  xAxisLabel,
  yAxisLabel,
  color = '#3b82f6',
  showGrid = true,
  showValues = false,
  height = 300,
  className,
  ...chartProps
}: BarChartProps) {
  const { normalizedData, padding } = useMemo(() => {
    if (data.length === 0) {
      return { normalizedData: [], padding: 40 };
    }

    const values = data.map((d) => d.value);
    const max = Math.max(...values, 0) || 1;
    const padding = 40;
    const chartHeight = height - padding * 2;
    const barWidth = (100 - padding * 2) / data.length / 1.5;
    const barSpacing = (100 - padding * 2) / data.length;

    const normalizedData = data.map((item, index) => {
      const heightPercent = (item.value / max) * (chartHeight / 10);
      const x = padding / 10 + (index * barSpacing) / 10;
      const y = 100 - padding / 10 - heightPercent;
      return {
        ...item,
        x,
        y,
        width: barWidth / 10,
        height: heightPercent,
      };
    });

    return { normalizedData, padding };
  }, [data, height]);

  if (data.length === 0) {
    return (
      <Chart height={height} className={className} {...chartProps}>
        <div className="flex h-full items-center justify-center text-muted-foreground">
          Aucune donnée disponible
        </div>
      </Chart>
    );
  }

  return (
    <Chart height={height} className={className} {...chartProps}>
      <svg
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        className="h-full w-full"
      >
        {/* Grid lines */}
        {showGrid && (
          <g stroke="currentColor" strokeWidth="0.1" opacity="0.2">
            {[0, 25, 50, 75, 100].map((y) => (
              <line
                key={y}
                x1={padding / 10}
                y1={y / 10}
                x2={100 - padding / 10}
                y2={y / 10}
              />
            ))}
          </g>
        )}

        {/* Y-axis labels */}
        {yAxisLabel && (
          <text
            x={padding / 10 - 2}
            y={50}
            textAnchor="middle"
            dominantBaseline="middle"
            transform={`rotate(-90 ${padding / 10 - 2} 50)`}
            className="fill-muted-foreground text-[2px]"
            fontSize="2"
          >
            {yAxisLabel}
          </text>
        )}

        {/* X-axis labels */}
        {xAxisLabel && (
          <text
            x={50}
            y={100 - padding / 10 + 4}
            textAnchor="middle"
            className="fill-muted-foreground text-[2px]"
            fontSize="2"
          >
            {xAxisLabel}
          </text>
        )}

        {/* Bars */}
        {normalizedData.map((bar, index) => (
          <g key={index}>
            <rect
              x={bar.x}
              y={bar.y}
              width={bar.width}
              height={bar.height}
              fill={color}
              className="cursor-pointer transition-opacity hover:opacity-80"
            >
              <title>
                {bar.label}: {data[index].value}
              </title>
            </rect>
            {showValues && (
              <text
                x={bar.x + bar.width / 2}
                y={bar.y - 1}
                textAnchor="middle"
                className="fill-foreground text-[1.5px]"
                fontSize="1.5"
              >
                {data[index].value}
              </text>
            )}
          </g>
        ))}
      </svg>
    </Chart>
  );
}
