import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";

interface MultiSelectProps {
  initialSelections?: string[];
  options: string[];
  onSave?: (selectedValues: string[]) => void;
  onCancel?: () => void;
  onUnmount?: (selectedValues: string[]) => void;
}

export const MultiSelect = ({
  initialSelections,
  options,
  onSave,
  onCancel,
  onUnmount,
}: MultiSelectProps) => {
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);

  const toggleItem = (item: string) => {
    setSelectedItems((prev) =>
      prev.includes(item) ? prev.filter((i) => i !== item) : [...prev, item],
    );
  };

  const handleSave = () => {
    console.log("Selected items:", selectedItems);
    if (onSave) {
      onSave(selectedItems);
    }
  };

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        if (onCancel) {
          onCancel();
        }
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    if (containerRef.current) {
      document.body.style.overflow = "hidden";
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.body.style.overflow = "auto";
      // if (onUnmount) {
      //   onUnmount(selectedItems);
      // }
    };
  }, [onCancel, onUnmount, selectedItems]);

  useEffect(() => {
    // something to do on first load when implementing endpoints
    console.log(initialSelections);
  }, [initialSelections]);

  return (
    <div
      ref={containerRef}
      className="w-full max-w-2xl mx-auto px-12 py-16 space-y-4 bg-[#F2F2F2] rounded-lg shadow-lg font-inter"
    >
      <div className="flex flex-wrap gap-2">
        {options.map((item) => (
          <button
            key={item}
            onClick={() => toggleItem(item)}
            className={`px-4 py-2 rounded-full text-sm transition-colors text-[9px]
              ${
                selectedItems.includes(item)
                  ? "bg-[#EF2424] text-white hover:bg-[#EF2424]"
                  : "bg-white text-[#000000] hover:bg-white"
              }`}
          >
            {item}
          </button>
        ))}
      </div>

      <div className="mt-6 flex justify-center items-center">
        <Button
          onClick={handleSave}
          className="bg-[#EF2424] hover:bg-[#EF2424] text-[9px]"
        >
          Save
        </Button>
      </div>
    </div>
  );
};
