import React, { useEffect, useId, useRef, useState } from "react";

export default function LogoImagePicker({
  value,
  icons,
  onChange,
  slotLabel,
  disabled = false,
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);
  const listId = useId();

  const selected = icons.find((ic) => String(ic.icon_id) === String(value));

  useEffect(() => {
    if (!open) return undefined;
    const onDocClick = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    const onKey = (e) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const pick = (iconId) => {
    onChange(iconId ? String(iconId) : "");
    setOpen(false);
  };

  return (
    <div
      className={`logo-image-picker${open ? " logo-image-picker--open" : ""}`}
      ref={rootRef}
    >
      <button
        type="button"
        className="logo-image-picker__trigger"
        onClick={() => !disabled && setOpen((v) => !v)}
        disabled={disabled}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-controls={listId}
        title={slotLabel}
      >
        {selected?.icon_data_url ? (
          <img
            src={selected.icon_data_url}
            alt=""
            className="logo-image-picker__trigger-img"
          />
        ) : (
          <span className="logo-image-picker__empty" aria-hidden="true">
            +
          </span>
        )}
      </button>

      {value ? (
        <button
          type="button"
          className="logo-image-picker__clear"
          onClick={() => onChange("")}
          disabled={disabled}
          aria-label={`Clear ${slotLabel}`}
          title="Remove"
        >
          ×
        </button>
      ) : null}

      {open ? (
        <div className="logo-image-picker__menu" id={listId} role="listbox">
          <button
            type="button"
            className="logo-image-picker__option logo-image-picker__option--none"
            onClick={() => pick("")}
            role="option"
            aria-selected={!value}
          >
            <span className="logo-image-picker__none-mark">—</span>
          </button>
          {icons.map((ic) => (
            <button
              key={ic.icon_id}
              type="button"
              className={`logo-image-picker__option${
                String(ic.icon_id) === String(value)
                  ? " logo-image-picker__option--selected"
                  : ""
              }`}
              onClick={() => pick(ic.icon_id)}
              role="option"
              aria-selected={String(ic.icon_id) === String(value)}
              title={`Logo ${ic.icon_id}`}
            >
              {ic.icon_data_url ? (
                <img src={ic.icon_data_url} alt="" />
              ) : (
                <span className="logo-image-picker__none-mark">?</span>
              )}
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}
