import React, { useEffect, useRef, useState } from "react";
import { KebebIcon, TickIcon } from "../../icons/ExportCommonIcons";

interface KebabMenuListMultiSelectProps {
  items: { id: string; name: string }[]; // Array of menu items with id and name
  onSelectionChange?: (selectedItems: string[]) => void; // Callback for selected items
}

const KebabMenuListMultiSelect: React.FC<KebabMenuListMultiSelectProps> = ({
  items,
  onSelectionChange,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const menuRef = useRef<HTMLDivElement>(null); // Ref to track the container

  const handleToggle = () => {
    setIsOpen((prev) => !prev);
  };

  const handleItemToggle = (id: string) => {
    setSelectedItems((prevSelected) => {
      const isAlreadySelected = prevSelected.includes(id);
      const updatedSelection = isAlreadySelected
        ? prevSelected.filter((item) => item !== id) // Deselect if already selected
        : [...prevSelected, id]; // Add to selection if not selected

      if (onSelectionChange) {
        onSelectionChange(updatedSelection);
      }

      return updatedSelection;
    });
  };

  // Close menu if clicked outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

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

  return (
    <div className="kebab-menu-container" ref={menuRef}>
      <div className="kebab-icon" onClick={handleToggle}>
        <KebebIcon />
      </div>
      {isOpen && (
        <div className="menu-list">
          {items.map((item) => (
            <div
              key={item.id}
              className={`menu-item ${
                selectedItems.includes(item.id) ? "selected" : ""
              }`}
              onClick={() => handleItemToggle(item.id)}
            >
              <input
                type="checkbox"
                checked={selectedItems.includes(item.id)}
                onChange={() => handleItemToggle(item.id)}
              />
              <div className="icon-container">
                {selectedItems.includes(item.id) && <TickIcon />}
              </div>
              {item.name}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default KebabMenuListMultiSelect;
