"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
import LoadingSpinner from "./LoadingSpinner";

export interface SelectOption {
  label: string;
  value: string;
}

interface MultiSelectPopupProps {
  options: SelectOption[];
  selected: (SelectOption | string)[];
  onClose: () => void;
  onChange: (updated: SelectOption[]) => void;
  onSaveApiCall?: any;
  loading?: boolean;
}

export default function MultiSelectPopup2({
  options,
  selected,
  onClose,
  onChange,
  onSaveApiCall,
  loading,
}: MultiSelectPopupProps) {
  const modalRef = useRef<HTMLDivElement>(null);

  // Normalize selected values to { label, value }
  const normalize = (sel: string | SelectOption): SelectOption => {
    if (typeof sel === "string") {
      const found = options.find((opt) => opt.value === sel || opt.label.toLowerCase() === sel.toLowerCase());
      return (
        found || {
          label: sel,
          value: sel.toLowerCase(),
        }
      );
    }
    return sel;
  };

  const [tempSelected, setTempSelected] = useState<SelectOption[]>(
    (selected || []).map(normalize)
  );

  useEffect(() => {
    setTempSelected((selected || []).map(normalize));
  }, [selected]);

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
      onClose();
    }
  };

  const toggleOption = (option: SelectOption) => {
    const exists = tempSelected.some((item) => item.value === option.value);
    if (exists) {
      setTempSelected(tempSelected.filter((item) => item.value !== option.value));
    } else {
      setTempSelected([...tempSelected, option]);
    }
  };

  const handleSave = async () => {
    try {
      onChange(tempSelected);

      if (onSaveApiCall) {
        await onSaveApiCall(tempSelected);
      }

      onClose();
    } catch (error) {
      console.error("Failed to save selection:", error);
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={handleBackdropClick}
    >
      <div
        ref={modalRef}
        className="bg-white p-6 rounded-lg w-[90%] max-w-[650px]"
      >
        <h3 className="text-lg font-semibold mb-4">Select Hobbies</h3>
        <div className="flex flex-wrap gap-3 max-h-60 overflow-y-auto">
          {options.map((opt) => {
            const isActive = tempSelected.some(
              (item) => item.value === opt.value
            );
            return (
              <button
                key={opt.value}
                onClick={() => toggleOption(opt)}
                className={cn(
                  "py-2 px-3 text-[0.75rem] rounded-full",
                  isActive
                    ? "bg-red-500 text-white"
                    : "bg-gray-200 text-black"
                )}
              >
                {opt.label}
              </button>
            );
          })}
        </div>
        <div className="mt-6 flex justify-end gap-4">
          <button onClick={onClose} className="text-gray-500">
            Cancel
          </button>
          <button
            onClick={handleSave}
            className="bg-red-500 text-white px-4 py-2 rounded"
            disabled={loading}
          >
            {loading ? <LoadingSpinner /> : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}
