import { useEffect, useRef, useState } from "react";
import { ChevronDown } from "lucide-react";

export interface SelectDropdownOption {
  value: string;
  label: string;
}

interface SelectDropdownProps {
  value: string;
  onChange: (value: string) => void;
  options: SelectDropdownOption[];
  placeholder?: string;
  variant?: "pill" | "ghost";
  "aria-label"?: string;
  disabled?: boolean;
}

export function SelectDropdown({
  value,
  onChange,
  options,
  placeholder = "Select…",
  variant = "pill",
  "aria-label": ariaLabel,
  disabled = false,
}: SelectDropdownProps) {
  const [open, setOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const selectedLabel =
    options.find((opt) => opt.value === value)?.label ?? placeholder;

  const disabledButtonClass = variant === "ghost"
    ? " opacity-50 cursor-not-allowed"
    : " disabled:opacity-50 disabled:cursor-not-allowed";

  useEffect(() => {
    if (!open) return;
    const handleMouseDown = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setOpen(false);
      }
    };
    // Use capture phase so we fire before React Flow's stopPropagation
    document.addEventListener("mousedown", handleMouseDown, true);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("mousedown", handleMouseDown, true);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [open]);

  const handleSelect = (nextValue: string) => {
    onChange(nextValue);
    setOpen(false);
  };

  const buttonClass = variant === "ghost"
    ? "flex items-center gap-1 text-sm text-text-muted hover:text-text transition-colors cursor-pointer"
    : "w-full flex items-center justify-between rounded-full bg-surface border border-border px-4 py-2 pr-10 text-sm text-text focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/50 transition-colors cursor-pointer";

  return (
    <div className="relative" ref={menuRef}>
      <button
        type="button"
        onClick={() => !disabled && setOpen((o) => !o)}
        aria-label={ariaLabel}
        disabled={disabled}
        className={buttonClass + (disabled ? disabledButtonClass : "")}
      >
        <span className="truncate">{selectedLabel}</span>
        <ChevronDown
          size={14}
          className={variant === "ghost" ? "text-text-muted" : "absolute right-3 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none"}
        />
      </button>
      {open && (
        <div className="absolute left-0 mt-1 rounded-xl bg-surface border border-border py-1 z-10 min-w-[200px] w-full shadow-lg">
          {options.map((opt) => (
            <button
              key={opt.value}
              type="button"
              className="flex items-center gap-2 px-3 py-2 text-sm text-text-muted hover:text-text hover:bg-surface-raised w-full text-left transition-colors cursor-pointer"
              onClick={() => handleSelect(opt.value)}
            >
              {opt.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}