'use client'
// src/components/charts/Heatmap.tsx
// Input: matrix (number[][]), rows, cols, colorScale function
// Output: animated grid heatmap with opacity stagger entry
// Rationale: anomaly detection visualization in Analyses screen

import { useEffect, useState } from 'react'
import { Tooltip } from '@/components/ui/Tooltip'

export interface HeatmapProps {
  matrix: number[][]
  rows: string[]
  cols: string[]
  colorScale?: (value: number, min: number, max: number) => string
  className?: string
  cellSize?: number
}

function defaultColorScale(value: number, min: number, max: number): string {
  const t = (value - min) / (max - min || 1)
  // bg-subtle → data-rose
  const r = Math.round(17 + (251 - 17) * t)
  const g = Math.round(27 + (113 - 27) * t)
  const b = Math.round(40 + (133 - 40) * t)
  return `rgb(${r},${g},${b})`
}

export function Heatmap({
  matrix,
  rows,
  cols,
  colorScale = defaultColorScale,
  className,
  cellSize = 28,
}: HeatmapProps) {
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    const t = setTimeout(() => setVisible(true), 80)
    return () => clearTimeout(t)
  }, [])

  const allValues = matrix.flat()
  const min = Math.min(...allValues)
  const max = Math.max(...allValues)

  return (
    <div className={className}>
      <div className="flex gap-0.5">
        {/* Row labels */}
        <div className="flex flex-col gap-0.5 mr-1">
          {/* Spacer for col labels row */}
          <div style={{ height: cellSize }} />
          {rows.map((row, ri) => (
            <div
              key={ri}
              style={{ height: cellSize }}
              className="flex items-center text-caption text-text-muted whitespace-nowrap pr-2"
            >
              {row}
            </div>
          ))}
        </div>
        <div className="flex flex-col gap-0.5">
          {/* Col labels */}
          <div className="flex gap-0.5">
            {cols.map((col, ci) => (
              <div
                key={ci}
                style={{ width: cellSize, height: cellSize }}
                className="flex items-end justify-center pb-1 text-caption text-text-muted"
              >
                {col.length > 3 ? col.slice(0, 3) : col}
              </div>
            ))}
          </div>
          {/* Cells */}
          {matrix.map((row, ri) => (
            <div key={ri} className="flex gap-0.5">
              {row.map((value, ci) => {
                const delay = (ri * cols.length + ci) * 8
                const bg = colorScale(value, min, max)
                return (
                  <Tooltip key={ci} content={`${rows[ri]} / ${cols[ci]}: ${value.toFixed(2)}`}>
                    <div
                      style={{
                        width: cellSize,
                        height: cellSize,
                        backgroundColor: bg,
                        opacity: visible ? 1 : 0,
                        transition: `opacity 0.3s ${delay}ms`,
                      }}
                      className="rounded-sm border border-bg-border/50 hover:border-accent-border cursor-default"
                    />
                  </Tooltip>
                )
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
