"use client";

import { useState } from "react";

/**
 * Renders a color swatch. Shows actual color when hex/code is valid; otherwise placeholder.
 * On hover, shows a custom tooltip with the color name (not the browser title).
 */

const KNOWN_COLOR_HEX: Record<string, string> = {
  black: "#000000",
  white: "#ffffff",
  red: "#dc2626",
  blue: "#2563eb",
  green: "#16a34a",
  yellow: "#eab308",
  orange: "#ea580c",
  pink: "#db2777",
  purple: "#9333ea",
  brown: "#78350f",
  grey: "#6b7280",
  gray: "#6b7280",
  beige: "#d4b896",
  navy: "#1e3a5f",
  gold: "#b8860b",
  silver: "#c0c0c0",
  cream: "#fffdd0",
  khaki: "#c3b091",
  maroon: "#800000",
  olive: "#808000",
  teal: "#008080",
};

function parseHex(value: string | null | undefined): string | null {
  if (!value || typeof value !== "string") return null;
  const s = value.trim().replace(/^#/, "");
  if (/^[0-9A-Fa-f]{6}$/.test(s)) return "#" + s;
  if (/^[0-9A-Fa-f]{3}$/.test(s)) {
    const r = s[0] + s[0], g = s[1] + s[1], b = s[2] + s[2];
    return "#" + r + g + b;
  }
  return null;
}

function hexForName(name: string | null | undefined): string | null {
  if (!name || typeof name !== "string") return null;
  const key = name.toLowerCase().trim();
  return KNOWN_COLOR_HEX[key] ?? null;
}

export interface ColorSwatchProps {
  /** Display name (e.g. "Red", "Navy") */
  name?: string | null;
  /** Hex or color code from backend (e.g. "#ff0000" or "FF0000") */
  hex?: string | null;
  /** Size of the swatch */
  size?: "sm" | "md" | "lg";
  /** Optional class for the wrapper */
  className?: string;
  /** Show name next to swatch (e.g. in product detail) */
  showName?: boolean;
}

export default function ColorSwatch({
  name,
  hex,
  size = "md",
  className = "",
  showName = false,
}: ColorSwatchProps) {
  const [showTooltip, setShowTooltip] = useState(false);

  const resolvedHex = parseHex(hex) ?? hexForName(name);
  const hasVerifiedColor = !!resolvedHex;
  const sizeClasses =
    size === "sm"
      ? "w-5 h-5 min-w-[20px]"
      : size === "lg"
        ? "w-8 h-8 min-w-[32px]"
        : "w-6 h-6 min-w-[24px]";
  const tooltipLabel = name && name.trim() ? name.trim() : "Color";

  return (
    <span
      className={`inline-flex items-center gap-1.5 relative ${className}`}
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
    >
      <span
        className={`inline-flex items-center justify-center rounded-full border-2 border-gray-200 flex-shrink-0 transition-transform hover:scale-110 ${sizeClasses} ${
          !hasVerifiedColor ? "bg-gray-100 text-gray-400" : "shadow-sm"
        }`}
        style={
          hasVerifiedColor
            ? { backgroundColor: resolvedHex ?? undefined }
            : undefined
        }
        aria-label={tooltipLabel}
      >
        {!hasVerifiedColor && (
          <span
            className="font-medium"
            style={{ fontSize: size === "sm" ? "8px" : size === "lg" ? "12px" : "10px" }}
          >
            ?
          </span>
        )}
      </span>
      {showTooltip && (
        <span
          className="absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-1.5 px-2 py-1 text-xs font-medium text-white bg-gray-900 rounded-md whitespace-nowrap pointer-events-none shadow-lg"
          role="tooltip"
        >
          {tooltipLabel}
        </span>
      )}
      {showName && (
        <span className="text-inherit text-sm truncate max-w-[120px]">
          {tooltipLabel}
        </span>
      )}
    </span>
  );
}
