import React, { useEffect, useRef, useState } from 'react';
import { PickerItem } from '../../../shared/types';

interface ItemPickerProps {
  items: PickerItem[];
  selection: string | undefined;
  label: string;
  placeholder: string;
  classModifier: string;
  valueFormatter?: (id: string, label: string) => string;
  onPick: (picked: string, id?: string) => void;
}

const ItemPicker: React.FC<ItemPickerProps> = ({ items, selection, label, placeholder, classModifier, valueFormatter, onPick }) => {
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement | null>(null);

  const handlePick = (picked: string, id?: string) => {
    setIsDropdownOpen(false);
    onPick(picked, id);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

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

  return (
    <div className={'dropdown__input ' + classModifier}>
      <span className="dropdown__label">{label}</span>
      <div className="dropdown" ref={dropdownRef}>
        <button className={`dropdown-toggle ${isDropdownOpen ? 'dropdown-toggle--open' : ''}`} onClick={() => setIsDropdownOpen((prev) => !prev)}>
          <span>{selection || placeholder}</span>
          <span className="arrow">&#9662;</span>
        </button>
        {isDropdownOpen && (
          <ul className="dropdown-menu">
            {items.map(({ id, label, icon }) => (
              <li
                key={label}
                onClick={(e) => {
                  handlePick(label, id);
                  e.stopPropagation();
                }}
                className={`dropdown-menu__item${selection === label ? ' dropdown-menu__item--selected' : ''}`}>
                {icon && <span className="travel-class-icon">{icon}</span>}
                {valueFormatter ? valueFormatter(id, label) : label}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
};

export default ItemPicker;
