import { Check, X } from "lucide-react";
import { useMemo } from "react";
import { useColorAttributes } from "~/requestHandler/use-product-hooks";

interface ColorSelectorProps {
  selectedColors: string[];
  onToggleColor: (colorValue: string) => void;
  onRemoveColor: (colorValue: string) => void;
  unselectedMode: boolean;
  onToggleUnselectedMode: (enabled: boolean) => void;
}

// The DB now carries a curated 81-color palette laid out as a 9×9 grid.
// Each AttributeValue's `info` object has:
//   persian     — display name in Persian
//   detail      — hex swatch color
//   sort_order  — 0..80, row-major position in the grid
//   grid_row    — 0..8
//   grid_col    — 0..8 (columns cluster by hue family)
// Anything without a numeric sort_order is treated as trailing so we don't
// accidentally hide legacy or admin-inserted values.
export const ColorSelector = ({
  selectedColors,
  onToggleColor,
  onRemoveColor,
  unselectedMode,
  onToggleUnselectedMode,
}: ColorSelectorProps) => {
  const { data: colors, isLoading } = useColorAttributes();

  const sortedColors = useMemo(() => {
    if (!colors) return [];
    return colors
      .filter((c) => c.value !== "UNSELECTED")
      .slice()
      .sort((a, b) => {
        const ax =
          typeof a.info?.sort_order === "number"
            ? a.info.sort_order
            : Number.MAX_SAFE_INTEGER;
        const bx =
          typeof b.info?.sort_order === "number"
            ? b.info.sort_order
            : Number.MAX_SAFE_INTEGER;
        return ax - bx;
      });
  }, [colors]);

  if (isLoading) {
    return (
      <div className="space-y-4">
        <h4 className="font-medium text-right">انتخاب رنگ های موجود:</h4>
        <div className="grid grid-cols-9 gap-1.5">
          {[...Array(81)].map((_, i) => (
            <div
              key={i}
              className="aspect-square rounded-md border border-WHITE2 bg-WHITE3 animate-pulse"
            />
          ))}
        </div>
      </div>
    );
  }

  // Perceived lightness of the swatch — controls whether we overlay a light
  // or dark checkmark for the "selected" state so it stays visible on both
  // near-white swatches (سفید, شیری) and near-black swatches (مشکی, بنفش تیره).
  const isDarkHex = (hex?: string) => {
    if (!hex) return false;
    const h = hex.replace("#", "");
    if (h.length !== 6) return false;
    const r = parseInt(h.slice(0, 2), 16);
    const g = parseInt(h.slice(2, 4), 16);
    const b = parseInt(h.slice(4, 6), 16);
    // Rec. 709 luma; below 128 reads as "dark ground -> use white ink".
    return 0.2126 * r + 0.7152 * g + 0.0722 * b < 128;
  };

  return (
    <div className="space-y-4">
      <h4 className="font-medium text-right">انتخاب رنگ های موجود:</h4>

      {/* Unselected Mode Switch */}
      <div className="flex items-center justify-between p-3 bg-GRAY3 rounded-lg">
        <span className="text-sm font-medium text-BLACK2">
          بدون مشخص کردن رنگ
        </span>
        <label className="relative inline-flex items-center cursor-pointer">
          <input
            type="checkbox"
            checked={unselectedMode}
            onChange={(e) => onToggleUnselectedMode(e.target.checked)}
            className="sr-only peer"
            aria-label="حالت بدون رنگ"
          />
          <div className="w-11 h-6 bg-WHITE2 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-WHITE after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-WHITE after:border-GRAY3 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-VITROWN_BLUE border"></div>
        </label>
      </div>

      {/* 9×9 palette: columns are hue families, rows go light -> dark. */}
      <div
        className={`${unselectedMode ? "opacity-50 pointer-events-none" : ""}`}
      >
        <div className="grid grid-cols-9 gap-1.5">
          {sortedColors.map((color) => {
            const isSelected = selectedColors.includes(color.value);
            const hex = color.info?.detail || "#000000";
            const dark = isDarkHex(hex);
            return (
              <button
                key={color.id ?? color.value}
                type="button"
                onClick={() => !unselectedMode && onToggleColor(color.value)}
                disabled={unselectedMode}
                title={color.info?.persian || color.value}
                aria-label={color.info?.persian || color.value}
                aria-pressed={isSelected}
                className={`relative aspect-square rounded-md border-2 transition-all ${
                  isSelected
                    ? "border-VITROWN_BLUE shadow-md"
                    : "border-WHITE2 hover:border-GRAY3"
                }`}
                style={{ backgroundColor: hex }}
              >
                {isSelected && (
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Check
                      className={`w-3.5 h-3.5 ${dark ? "text-WHITE" : "text-BLACK"}`}
                    />
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Selected Colors Display */}
      {selectedColors.length > 0 && !unselectedMode && (
        <div className="flex flex-wrap gap-2 mt-3">
          {selectedColors.map((colorValue) => {
            const colorInfo = sortedColors.find((c) => c.value === colorValue);
            const hex = colorInfo?.info?.detail || "#EEE";
            return (
              <div
                key={colorValue}
                className="flex items-center gap-1.5 bg-WHITE3 px-3 py-1 rounded-full text-sm"
              >
                <div
                  className="w-3 h-3 rounded-full border border-GRAY3"
                  style={{ backgroundColor: hex }}
                />
                <span>{colorInfo?.info?.persian || colorValue}</span>
                <X
                  className="w-4 h-4 cursor-pointer text-red-400"
                  onClick={() => onRemoveColor(colorValue)}
                />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};
