import { Palette } from "lucide-react";
import { useEffect, useRef, useState, type InputHTMLAttributes } from "react";
import useOutsideDismiss from "../hooks/useOutsideDismiss";
import { i18nMessage } from "../i18n/LanguageContext";

type ColorPickerFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> & {
  value: string;
  onChange: (value: string) => void;
  swatches?: string[];
};

const DEFAULT_SWATCHES = [
"#4f8cff", "#38a169", "#d69e2e", "#e53e3e", "#805ad5", "#319795",
"#dd6b20", "#718096", "#1f2937", "#f59e0b", "#10b981", "#ef4444"];


const HEX_PATTERN = /^#[0-9a-fA-F]{6}$/;

function normalizeColor(value: string): string {
  const trimmed = value.trim();
  if (/^[0-9a-fA-F]{6}$/.test(trimmed)) return `#${trimmed}`;
  return trimmed;
}

export default function ColorPickerField({
  value,
  onChange,
  swatches = DEFAULT_SWATCHES,
  disabled,
  className = "",
  placeholder = "#4f8cff",
  ...props
}: ColorPickerFieldProps) {
  const [open, setOpen] = useState(false);
  const rootRef = useOutsideDismiss(open, () => setOpen(false));
  const inputRef = useRef<HTMLInputElement | null>(null);
  const normalizedValue = normalizeColor(value || "");
  const previewColor = HEX_PATTERN.test(normalizedValue) ? normalizedValue : "transparent";

  useEffect(() => {
    const input = inputRef.current;
    if (!input) return;
    input.setCustomValidity(normalizedValue && !HEX_PATTERN.test(normalizedValue) ? "i18n:govoplan-core.use_a_six_digit_hex_color_for_example_4f8cff.d74f4ad2" : "");
  }, [normalizedValue]);

  function selectColor(nextColor: string) {
    onChange(nextColor);
    setOpen(false);
  }

  return (
    <div ref={rootRef} className={`color-picker-field ${className}`.trim()}>
      <span className="color-picker-preview" style={{ backgroundColor: previewColor }} aria-hidden="true" />
      <input
        {...props}
        ref={inputRef}
        type="text"
        inputMode="text"
        pattern="#[0-9a-fA-F]{6}"
        value={value}
        placeholder={placeholder}
        disabled={disabled}
        onChange={(event) => onChange(normalizeColor(event.target.value))} />
      
      <button type="button" className="color-picker-trigger" onClick={() => !disabled && setOpen((current) => !current)} disabled={disabled} aria-label="i18n:govoplan-core.choose_color.09b969bb">
        <Palette size={16} />
      </button>
      {open &&
      <div className="color-picker-popover" role="dialog" aria-label="i18n:govoplan-core.color_picker.91dee962">
          <div className="color-picker-grid">
            {swatches.map((swatch) =>
          <button
            key={swatch}
            type="button"
            className={swatch.toLowerCase() === normalizedValue.toLowerCase() ? "is-selected" : ""}
            style={{ backgroundColor: swatch }}
            onClick={() => selectColor(swatch)}
            aria-label={i18nMessage("i18n:govoplan-core.use_value.bac38fc3", { value0: swatch })} />

          )}
          </div>
        </div>
      }
    </div>);

}
