// Heatmap Component
import { ResponsiveContainer, Cell } from 'recharts';
import './Heatmap.css';

interface HeatmapCell {
  x: string;
  y: string;
  value: number;
  label?: string;
}

interface HeatmapProps {
  data: HeatmapCell[];
  xLabels: string[];
  yLabels: string[];
  colorScale?: (value: number) => string;
  height?: number;
}

const defaultColorScale = (value: number): string => {
  if (value >= 0.8) return '#ef4444'; // Red - high risk
  if (value >= 0.6) return '#f59e0b'; // Orange - medium-high
  if (value >= 0.4) return '#fbbf24'; // Yellow - medium
  if (value >= 0.2) return '#84cc16'; // Light green - low-medium
  return '#10b981'; // Green - low risk
};

export default function Heatmap({
  data,
  xLabels,
  yLabels,
  colorScale = defaultColorScale,
  height = 400,
}: HeatmapProps) {
  const maxValue = Math.max(...data.map((d) => d.value));
  const minValue = Math.min(...data.map((d) => d.value));

  return (
    <div className="heatmap" style={{ height, '--cols': xLabels.length, '--rows': yLabels.length } as React.CSSProperties}>
      <div className="heatmap__container">
        <div className="heatmap__y-axis">
          {yLabels.map((label) => (
            <div key={label} className="heatmap__y-label">
              {label}
            </div>
          ))}
        </div>
        <div className="heatmap__grid">
          <div className="heatmap__x-axis">
            {xLabels.map((label) => (
              <div key={label} className="heatmap__x-label">
                {label}
              </div>
            ))}
          </div>
          <div className="heatmap__cells">
            {yLabels.map((yLabel) =>
              xLabels.map((xLabel) => {
                const cell = data.find((d) => d.x === xLabel && d.y === yLabel);
                const value = cell?.value ?? 0;
                const normalizedValue = maxValue > minValue ? (value - minValue) / (maxValue - minValue) : 0;

                return (
                  <div
                    key={`${xLabel}-${yLabel}`}
                    className="heatmap__cell"
                    style={{
                      backgroundColor: colorScale(normalizedValue),
                      opacity: cell ? 0.8 : 0.2,
                    }}
                    title={cell ? `${cell.label || `${xLabel} - ${yLabel}`}: ${value.toFixed(2)}` : 'No data'}
                  >
                    {cell && <span className="heatmap__cell-value">{value.toFixed(2)}</span>}
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>
      <div className="heatmap__legend">
        <span>Low</span>
        <div className="heatmap__legend-gradient" />
        <span>High</span>
      </div>
    </div>
  );
}

