import { useState, useEffect, useRef } from "react";
import { ChevronDownIcon } from "../../icons";

interface Option {
  value: string;
  label: string;
  icon?: React.ReactNode;
}

interface SelectDropdownProps {
  options: Option[];
  placeholder?: string;
  onChange: (value: string) => void;
  className?: string;
  defaultValue?: string;
  value?: string; // Controlled value
  disabled?: boolean;
}

const SelectDropdown: React.FC<SelectDropdownProps> = ({
  options,
  placeholder = "Select an option",
  onChange,
  className = "",
  defaultValue = "",
  value,
  disabled = false,
}) => {
  const isControlled = value !== undefined;
  const [isOpen, setIsOpen] = useState(false);
  const [internalValue, setInternalValue] = useState<string>(defaultValue);
  // For controlled components, always use the value prop; for uncontrolled, use internal state
  const selectedValue = isControlled ? (value || '') : internalValue;
  const dropdownRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Sync internalValue with defaultValue when it changes externally (only for uncontrolled)
  useEffect(() => {
    if (!isControlled) {
      setInternalValue(defaultValue);
    }
  }, [defaultValue, isControlled]);

  // When controlled, ensure selectedValue updates when value prop changes
  // selectedValue is computed directly from value prop, no effect needed

  // Get selected label - normalize values for comparison
  const normalizedSelectedValue = String(selectedValue || '');
  const selectedOption = options.find((opt) => String(opt.value || '') === normalizedSelectedValue);
  const displayText = selectedOption ? selectedOption.label : placeholder;
  const isPlaceholder = !selectedOption;

  // Handle click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => {
        document.removeEventListener("mousedown", handleClickOutside);
      };
    }
  }, [isOpen]);

  // Handle option selection
  const handleSelect = (val: string | undefined) => {
    // Normalize: undefined/null becomes empty string for "All" options
    const selectedVal = val === null || val === undefined ? '' : String(val);
    if (!isControlled) {
      setInternalValue(selectedVal);
    }
    // Always call onChange - this should trigger parent state update
    onChange(selectedVal);
    setIsOpen(false);
  };

  // Handle keyboard navigation
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Escape") {
      setIsOpen(false);
    } else if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      setIsOpen(!isOpen);
    }
  };

  return (
    <div className={`relative ${className}`}>
      {/* Trigger Button - styled like igny8-select-styled */}
      <button
        ref={buttonRef}
        type="button"
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        onKeyDown={handleKeyDown}
        className={`igny8-select-styled h-9 w-full appearance-none rounded-lg border border-gray-300 bg-transparent px-3 py-2 pr-10 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:focus:border-brand-800 ${
          isPlaceholder
            ? "text-gray-400 dark:text-gray-400"
            : "text-gray-800 dark:text-white/90"
        } ${
          isOpen
            ? "border-brand-300 ring-3 ring-brand-500/10 dark:border-brand-800"
            : ""
        } ${disabled ? "opacity-50 cursor-not-allowed" : ""}`}
      >
        <span className="block text-left truncate">{displayText}</span>
        <span className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
          <ChevronDownIcon className={`h-4 w-4 text-gray-400 transition-transform ${isOpen ? 'transform rotate-180' : ''}`} />
        </span>
      </button>

      {/* Dropdown Menu - styled like Dropdown component but compact */}
      {isOpen && (
        <div
          ref={dropdownRef}
          className="absolute z-50 left-0 right-0 mt-1 rounded-lg border border-gray-200 bg-white shadow-theme-lg dark:border-gray-800 dark:bg-gray-dark overflow-hidden max-h-60 overflow-y-auto"
        >
          <div className="py-1">
            {options.map((option) => {
              const optionValue = String(option.value || ''); // Normalize option value
              const normalizedSelected = String(selectedValue || '');
              // Compare values strictly
              const isSelected = normalizedSelected === optionValue;
              return (
                <button
                  key={`option-${option.value || 'empty'}-${option.label}`}
                  type="button"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    // Pass the normalized optionValue to ensure consistency
                    handleSelect(optionValue);
                  }}
                  className={`w-full text-left px-3 py-2 text-sm transition-colors flex items-center gap-2 ${
                    isSelected
                      ? "bg-brand-500 text-white"
                      : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
                  }`}
                >
                  {option.icon && <span className="flex-shrink-0">{option.icon}</span>}
                  <span>{option.label}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

export default SelectDropdown;

