import React, { useMemo, useState } from 'react';

type StackedDataset = {
  name: string;
  values: number[];
  color: string;
};

type StackedBarChartProps = {
  labels: string[];
  datasets: StackedDataset[];
};

const StackedBarChart: React.FC<StackedBarChartProps> = ({
  labels,
  datasets,
}) => {
  const [tooltip, setTooltip] = useState<{ x: number; y: number; text: string } | null>(null);

  const rowTotals = useMemo(
    () =>
      labels.map((_, index) =>
        datasets.reduce((sum, dataset) => sum + (Number(dataset.values[index]) || 0), 0)
      ),
    [labels, datasets]
  );

  const maxTotal = useMemo(() => Math.max(...rowTotals, 1), [rowTotals]);

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

  return (
    <div className="relative" onMouseLeave={() => setTooltip(null)}>
      {tooltip && (
        <div
          className="fixed z-[90] pointer-events-none rounded-md bg-gray-900 text-white text-xs px-2 py-1 shadow-lg"
          style={{ left: tooltip.x + 12, top: tooltip.y + 12 }}
        >
          {tooltip.text}
        </div>
      )}

      <div className="max-h-72 overflow-y-auto pr-1 space-y-2">
        {labels.map((label, rowIndex) => {
          const total = rowTotals[rowIndex] || 0;
          return (
            <div key={`${label}-${rowIndex}`} className="grid grid-cols-[120px_1fr_36px] gap-2 items-center">
              <div
                className="text-xs text-gray-700 dark:text-gray-300 truncate"
                title={label}
              >
                {label}
              </div>
              <div className="h-7 bg-gray-100 dark:bg-gray-700/60 rounded-md overflow-hidden flex">
                {datasets.map(dataset => {
                  const value = Number(dataset.values[rowIndex]) || 0;
                  if (value <= 0) return null;
                  const widthPct = (value / maxTotal) * 100;
                  return (
                    <div
                      key={`${dataset.name}-${rowIndex}`}
                      className="h-full transition-opacity hover:opacity-85 cursor-pointer"
                      style={{
                        width: `${widthPct}%`,
                        backgroundColor: dataset.color,
                        minWidth: value > 0 ? '4px' : 0,
                      }}
                      onMouseEnter={e =>
                        setTooltip({
                          x: e.clientX,
                          y: e.clientY,
                          text: `${label}: ${dataset.name.replace('_', ' ')} = ${value}`,
                        })
                      }
                      onMouseMove={e =>
                        setTooltip({
                          x: e.clientX,
                          y: e.clientY,
                          text: `${label}: ${dataset.name.replace('_', ' ')} = ${value}`,
                        })
                      }
                    />
                  );
                })}
              </div>
              <div className="text-xs font-semibold text-gray-700 dark:text-gray-200 text-right">
                {total}
              </div>
            </div>
          );
        })}
      </div>

      <div className="flex flex-wrap items-center gap-3 mt-3 pt-2 border-t border-gray-200 dark:border-gray-700">
        {datasets.map(dataset => (
          <div key={dataset.name} className="flex items-center gap-1.5">
            <span className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: dataset.color }} />
            <span className="text-xs text-gray-600 dark:text-gray-400 capitalize">
              {dataset.name.replace('_', ' ')}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default StackedBarChart;
