import { useState, useRef, useEffect } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';

export const Dropdown = ({
  trigger,
  items = [],
  position = 'bottom-left',
  className = '',
  ...props
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

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

  const positionClasses = {
    'bottom-left': 'top-full left-0 mt-1',
    'bottom-right': 'top-full right-0 mt-1',
    'top-left': 'bottom-full left-0 mb-1',
    'top-right': 'bottom-full right-0 mb-1',
  };

  return (
    <div className={`relative inline-block ${className}`} ref={dropdownRef} {...props}>
      <div onClick={() => setIsOpen(!isOpen)}>
        {trigger || (
          <button className="p-2 rounded-lg hover:bg-gray-100">
            <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 12.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 18.75a.75.75 0 110-1.5.75.75 0 010 1.5z" />
            </svg>
          </button>
        )}
      </div>
      {isOpen && (
        <div
          className={`absolute z-50 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 ${positionClasses[position]}`}
        >
          {items.map((item, index) => (
            <button
              key={index}
              onClick={() => {
                if (item.onClick) {
                  item.onClick();
                }
                setIsOpen(false);
              }}
              className={`
                w-full text-left px-4 py-2 text-sm
                ${item.danger ? 'text-red-600 hover:bg-red-50' : 'text-gray-700 hover:bg-gray-100'}
                ${item.disabled ? 'opacity-50 cursor-not-allowed' : ''}
              `}
              disabled={item.disabled}
            >
              <div className="flex items-center">
                {item.icon && (
                  <Icon name={item.icon} className="mr-3 h-5 w-5" />
                )}
                {item.label}
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

export default Dropdown;

