import React, { useState, useMemo, useCallback } from "react";
import type { HeatmapTechnique } from "../../api/heatmap";
import HeatmapTooltip from "./HeatmapTooltip";

interface HeatmapCellProps {
  technique: HeatmapTechnique;
  size: "compact" | "normal" | "expanded";
  onClick: (techniqueId: string) => void;
}

/**
 * Memoized heatmap cell — this component renders 3000+ times in the
 * full ATT&CK matrix, so React.memo prevents unnecessary re-renders
 * when only sibling cells change.
 */
const HeatmapCell = React.memo(function HeatmapCell({ technique, size, onClick }: HeatmapCellProps) {
  const [showTooltip, setShowTooltip] = useState(false);

  const sizeClasses = {
    compact: "h-6 text-[9px] px-1",
    normal: "h-9 text-[11px] px-1.5",
    expanded: "h-14 text-xs px-2",
  };

  const bgColor = technique.enabled ? technique.color : "transparent";
  const isDisabled = !technique.enabled;

  // Memoize text color (derived from background hex)
  const textColor = useMemo(() => {
    const hex = bgColor;
    if (!hex || hex === "transparent" || hex === "") return "text-gray-600";
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;
    return brightness > 128 ? "text-gray-900" : "text-white";
  }, [bgColor]);

  // Status indicators — memoized
  const { testsCount, reviewRequired, isValidated } = useMemo(() => {
    const hasTests = technique.metadata.find((m) => m.name === "tests_count");
    return {
      testsCount: hasTests ? parseInt(hasTests.value, 10) : 0,
      reviewRequired: technique.comment?.toLowerCase().includes("review") ?? false,
      isValidated: technique.score >= 100,
    };
  }, [technique.metadata, technique.comment, technique.score]);

  const handleClick = useCallback(() => onClick(technique.techniqueID), [onClick, technique.techniqueID]);

  return (
    <div
      className="relative"
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
    >
      <button
        onClick={handleClick}
        disabled={isDisabled}
        className={`
          w-full rounded border transition-all duration-150
          ${sizeClasses[size]}
          ${isDisabled
            ? "cursor-default border-gray-800/30 bg-gray-900/20 opacity-30"
            : "cursor-pointer border-gray-700/50 hover:brightness-110 hover:ring-1 hover:ring-cyan-400/40"
          }
          ${reviewRequired && !isDisabled ? "ring-1 ring-amber-400/60" : ""}
          flex items-center gap-1 overflow-hidden
        `}
        style={{
          backgroundColor: isDisabled ? undefined : bgColor,
        }}
      >
        <span className={`truncate font-mono font-medium leading-tight ${textColor}`}>
          {technique.techniqueID}
        </span>
        {size !== "compact" && !isDisabled && (
          <span className="ml-auto flex items-center gap-0.5 flex-shrink-0">
            {testsCount === 0 && <span className="text-[8px]" title="No tests">&#x1F534;</span>}
            {reviewRequired && <span className="text-[8px]" title="Review required">&#x26A0;&#xFE0F;</span>}
            {isValidated && <span className="text-[8px]" title="Validated">&#x2705;</span>}
          </span>
        )}
      </button>

      {showTooltip && technique.enabled && (
        <div className="absolute left-full top-0 z-50 ml-2">
          <HeatmapTooltip technique={technique} />
        </div>
      )}
    </div>
  );
});

export default HeatmapCell;
