import React, { useState, useRef, useEffect } from 'react';
import { X, ChevronDown } from 'lucide-react';

interface Option {
  value: string;
  label: string;
}

interface MultiSelectProps {
  options: Option[];
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
  disabled?: boolean;
}

export const MultiSelect: React.FC<MultiSelectProps> = ({
  options,
  value = [],
  onChange,
  placeholder = "Select options...",
  disabled = false
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleToggle = (optionValue: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (disabled) return;
    
    if (value.includes(optionValue)) {
      onChange(value.filter(v => v !== optionValue));
    } else {
      onChange([...value, optionValue]);
    }
  };

  const handleRemove = (optionValue: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (disabled) return;
    onChange(value.filter(v => v !== optionValue));
  };

  const selectedOptions = options.filter(opt => value.includes(opt.value));

  return (
    <div className="relative w-full" ref={containerRef}>
      <div 
        className={`min-h-[44px] w-full rounded-lg border border-gray-300 bg-transparent px-3 py-1.5 flex items-center justify-between cursor-pointer ${disabled ? 'opacity-60 cursor-not-allowed bg-gray-50' : ''}`}
        onClick={() => !disabled && setIsOpen(!isOpen)}
      >
        <div className="flex flex-wrap gap-2 items-center flex-1">
          {selectedOptions.length === 0 ? (
            <span className="text-gray-400 text-sm py-1 px-1">{placeholder}</span>
          ) : (
            selectedOptions.map(opt => (
              <span 
                key={opt.value} 
                className="inline-flex items-center gap-1.5 bg-[#f4f6f8] text-[#334155] px-3 py-1.5 rounded-full text-sm font-medium"
              >
                {opt.label}
                <span 
                  className="cursor-pointer text-gray-500 hover:text-gray-700 transition-colors" 
                  onClick={(e) => handleRemove(opt.value, e)}
                >
                  <X size={14} />
                </span>
              </span>
            ))
          )}
        </div>
        <div className="text-gray-500 pl-2 ml-auto shrink-0 flex items-center">
          <ChevronDown size={20} className={`transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
        </div>
      </div>

      {isOpen && !disabled && (
        <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
          {options.length === 0 ? (
            <div className="p-3 text-sm text-gray-500">No options available</div>
          ) : (
            options.map((opt, index) => {
              const isSelected = value.includes(opt.value);
              return (
                <div
                  key={opt.value}
                  className={`px-4 py-3 text-sm cursor-pointer hover:bg-gray-50 transition-colors ${index !== options.length - 1 ? 'border-b border-gray-100' : ''} ${isSelected ? 'bg-gray-50/50' : ''}`}
                  onClick={(e) => handleToggle(opt.value, e)}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-gray-700">{opt.label}</span>
                    {isSelected && (
                      <span className="w-2 h-2 rounded-full bg-brand-950"></span>
                    )}
                  </div>
                </div>
              );
            })
          )}
        </div>
      )}
    </div>
  );
};
