// File: src/components/UIX/IconDropdown/IconDropdown.jsx

import React, { useState, useRef, useEffect, memo, useMemo, useCallback } from "react";
import { ChevronDownIcon, CheckIcon } from "@heroicons/react/24/outline";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";

/**
 * IconDropdown Component - Performance Optimized
 * Dropdown selector with support for icons and descriptions per option
 *
 * Perfect for permission selectors, role pickers, or any dropdown where
 * visual icons help users understand their choices.
 *
 * Performance optimizations:
 * - Component memoization with React.memo
 * - Memoized theme classes to prevent multiple getThemeClasses calls
 * - Optimized event handlers with useCallback
 * - Click-outside detection with useRef
 * - Prevented unnecessary re-renders
 *
 * @param {string} label - Dropdown label
 * @param {Array} options - Array of {value, label, description, icon, color?} objects
 * @param {string} value - Selected value
 * @param {function} onChange - Change handler (receives the value)
 * @param {boolean} disabled - Whether dropdown is disabled
 * @param {boolean} required - Whether selection is required
 * @param {string} className - Additional CSS classes
 */
const IconDropdown = memo(function IconDropdown({
  label,
  options = [],
  value,
  onChange,
  disabled = false,
  required = false,
  className = "",
}) {
  const { getThemeClasses } = useUIXTheme();
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  // Memoize all theme classes
  const themeClasses = useMemo(
    () => ({
      textPrimary: getThemeClasses("text-primary"),
      textSecondary: getThemeClasses("text-secondary"),
      textMuted: getThemeClasses("text-muted"),
      textAccent: getThemeClasses("text-accent"),
      textDanger: getThemeClasses("text-danger"),
      bgCard: getThemeClasses("bg-card"),
      bgInput: getThemeClasses("bg-input"),
      bgMuted: getThemeClasses("bg-muted"),
      bgAccentLight: getThemeClasses("bg-accent-light"),
      borderSecondary: getThemeClasses("border-secondary"),
      inputFocus: getThemeClasses("input-focus"),
      hoverBgMuted: getThemeClasses("hover:bg-muted"),
    }),
    [getThemeClasses],
  );

  // Find current selection
  const currentOption = useMemo(
    () => options.find((opt) => opt.value === value) || options[0],
    [options, value],
  );

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

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

  // Handle option selection
  const handleSelect = useCallback(
    (selectedValue) => {
      if (!disabled && onChange) {
        onChange(selectedValue);
        setIsOpen(false);
      }
    },
    [disabled, onChange],
  );

  // Toggle dropdown
  const handleToggle = useCallback(() => {
    if (!disabled) {
      setIsOpen((prev) => !prev);
    }
  }, [disabled]);

  return (
    <div className={className}>
      {label && (
        <label className={`block text-sm font-medium ${themeClasses.textPrimary} mb-1`}>
          {label}
          {required && (
            <span className={`ml-1 ${themeClasses.textDanger}`}>*</span>
          )}
        </label>
      )}

      <div className="relative" ref={dropdownRef}>
        {/* Trigger Button */}
        <button
          type="button"
          onClick={handleToggle}
          disabled={disabled}
          className={`w-full px-3 py-2 border ${themeClasses.borderSecondary} rounded-lg ${themeClasses.inputFocus} flex items-center justify-between text-left ${themeClasses.bgInput} ${
            disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
          }`}
        >
          <div className="flex items-center">
            {currentOption?.icon && (
              <currentOption.icon
                className={`h-5 w-5 mr-3 ${currentOption.color || themeClasses.textPrimary}`}
              />
            )}
            <div>
              <p className={`font-medium ${themeClasses.textPrimary}`}>
                {currentOption?.label || "Select an option"}
              </p>
              {currentOption?.description && (
                <p className={`text-xs ${themeClasses.textSecondary}`}>
                  {currentOption.description}
                </p>
              )}
            </div>
          </div>
          <ChevronDownIcon
            className={`h-5 w-5 ${themeClasses.textMuted} transition-transform duration-200 ${
              isOpen ? "rotate-180" : ""
            }`}
          />
        </button>

        {/* Dropdown Menu */}
        {isOpen && (
          <>
            <div
              className="fixed inset-0 z-10"
              onClick={() => setIsOpen(false)}
            />
            <div
              className={`absolute top-full mt-2 w-full ${themeClasses.bgCard} rounded-lg shadow-xl border ${themeClasses.borderSecondary} py-2 z-20`}
            >
              {options.map((option) => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => handleSelect(option.value)}
                  className={`w-full px-4 py-3 flex items-center ${themeClasses.hoverBgMuted} transition-colors duration-200 ${
                    value === option.value ? themeClasses.bgAccentLight : ""
                  }`}
                >
                  {option.icon && (
                    <option.icon
                      className={`h-5 w-5 mr-3 ${option.color || themeClasses.textPrimary}`}
                    />
                  )}
                  <div className="text-left flex-1">
                    <p
                      className={`font-medium ${
                        value === option.value
                          ? themeClasses.textAccent
                          : themeClasses.textPrimary
                      }`}
                    >
                      {option.label}
                    </p>
                    {option.description && (
                      <p className={`text-xs ${themeClasses.textSecondary}`}>
                        {option.description}
                      </p>
                    )}
                  </div>
                  {value === option.value && (
                    <CheckIcon className={`h-5 w-5 ${themeClasses.textAccent}`} />
                  )}
                </button>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
});

export default IconDropdown;
