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

const MultiSelect = ({
  name,
  label,
  options,
  selectedOptions,
  onChange,
  errorMsg,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef(null);

  const handleSelect = (option) => {
    const isSelected = selectedOptions.some(
      (selected) => selected.id === option.id
    );
    let newSelectedOptions;
    if (isSelected) {
      newSelectedOptions = selectedOptions.filter(
        (selected) => selected.id !== option.id
      );
    } else {
      newSelectedOptions = [...selectedOptions, option];
    }
    onChange(newSelectedOptions);
  };

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

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

  return (
    <div ref={containerRef}>
      <div className="relative mt-1">
        <button
          type="button"
          className="w-full bg-white border border-gray-300 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-pointer focus:outline-none sm:text-sm hover:border-primary focus:border-primary"
          onClick={() => setIsOpen(!isOpen)}
        >
          {selectedOptions.length > 0 ? (
            <div className="flex flex-wrap gap-1 justify-center items-center">
              {selectedOptions.map((option) => (
                <span
                  key={option.id}
                  className="bg-primary/10 text-secondary px-2 py-1 rounded-md text-sm"
                >
                  {option.name}
                </span>
              ))}
            </div>
          ) : (
            <span>{label}</span>
          )}
          <ChevronDown className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none h-full w-5" />
        </button>
        {isOpen && (
          <ul className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm">
            {options.map((option) => (
              <li
                key={option.id}
                className={`cursor-pointer select-none relative py-2 pl-3 pr-9 ${
                  selectedOptions.some((selected) => selected.id === option.id)
                    ? 'text-white bg-primary'
                    : 'text-gray-900 hover:bg-primary/10 hover:text-secondary'
                }`}
                onClick={() => handleSelect(option)}
              >
                <span
                  className={`block truncate ${selectedOptions.some((selected) => selected.id === option.id) ? 'font-semibold' : 'font-normal'}`}
                >
                  {option.name}
                </span>
                {selectedOptions.some(
                  (selected) => selected.id === option.id
                ) && (
                  <span className="absolute inset-y-0 right-0 flex items-center pr-4 text-white">
                    <Check className="h-5 w-5" />
                  </span>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>
      {errorMsg && <p className="mt-2 text-sm text-red-600">{errorMsg}</p>}
    </div>
  );
};

export default MultiSelect;
