import React, { useMemo } from 'react';

type HorizontalBarDataset = {
  name: string;
  values: number[];
  colors?: string[];
};

type HorizontalBarChartProps = {
  labels: string[];
  datasets: HorizontalBarDataset[];
  valueLabel?: string;
};

const HorizontalBarChart: React.FC<HorizontalBarChartProps> = ({
  labels,
  datasets,
  valueLabel = '',
}) => {
  const primaryDataset = datasets[0];
  const values = primaryDataset?.values || [];

  const maxValue = useMemo(() => Math.max(...values.map(value => Number(value) || 0), 1), [values]);

  if (!labels.length || !primaryDataset) {
    return (
      <div className="h-48 flex items-center justify-center text-gray-400 text-xs">
        No chart data available
      </div>
    );
  }

  const formatValue = (value: number) => {
    const rounded = Math.round(value * 100) / 100;
    return valueLabel ? `${rounded} ${valueLabel}` : String(rounded);
  };

  return (
    <div className="max-h-72 overflow-y-auto pr-1 space-y-2">
      {labels.map((label, rowIndex) => {
        const value = Number(values[rowIndex]) || 0;
        const widthPct = (value / maxValue) * 100;

        return (
          <div key={`${label}-${rowIndex}`} className="grid grid-cols-[7rem_1fr_auto] gap-2 items-center">
            <div className="text-xs text-gray-700 dark:text-gray-300 truncate text-right" title={label}>
              {label}
            </div>
            <div className="h-7 bg-gray-100 dark:bg-gray-700/60 rounded-md overflow-hidden">
              <div
                className="h-full rounded-md bg-gradient-to-r from-indigo-500 to-purple-500 transition-opacity"
                style={{
                  width: `${widthPct}%`,
                  minWidth: value > 0 ? '4px' : 0,
                }}
              />
            </div>
            <div className="text-xs font-semibold text-gray-700 dark:text-gray-200 whitespace-nowrap">
              {formatValue(value)}
            </div>
          </div>
        );
      })}
    </div>
  );
};

export default HorizontalBarChart;
