import React, { useState, useMemo } from 'react';
import * as LucideIcons from 'lucide-react';
import { Search, X } from 'lucide-react';

const popularIcons = [
  'Sparkles', 'Star', 'Award', 'Shield', 'Heart', 'Crown', 'Gem',
  'Zap', 'Wifi', 'Coffee', 'Utensils', 'Bed', 'Home', 'MapPin',
  'Phone', 'Mail', 'Calendar', 'Clock', 'Users', 'UserCheck',
  'Car', 'Plane', 'Ship', 'Train', 'Bike', 'Umbrella', 'Sun',
  'Moon', 'Cloud', 'Droplet', 'Flame', 'TreePine', 'Mountain',
  'Palette', 'Music', 'Camera', 'Video', 'Gamepad2', 'Book',
  'Briefcase', 'ShoppingBag', 'Gift', 'Trophy', 'Medal', 'Ribbon',
  'CheckCircle', 'XCircle', 'AlertCircle', 'Info', 'HelpCircle',
  'Lock', 'Key', 'Eye', 'EyeOff', 'Bell', 'Settings', 'Menu',
  'Grid', 'List', 'Layout', 'Maximize', 'Minimize', 'ArrowRight',
  'ArrowLeft', 'ArrowUp', 'ArrowDown', 'ChevronRight', 'ChevronLeft',
  'ChevronUp', 'ChevronDown', 'Plus', 'Minus', 'X', 'Check',
  'Trash2', 'Edit', 'Save', 'Download', 'Upload', 'Share',
  'Copy', 'Scissors', 'FileText', 'Image', 'Film', 'Headphones',
  'Mic', 'Radio', 'Tv', 'Monitor', 'Laptop', 'Smartphone',
  'Tablet', 'Watch', 'Printer', 'HardDrive', 'Database', 'Server',
  'Cloud', 'Globe', 'Compass', 'Navigation', 'Map', 'Route',
  'Building', 'Building2', 'Hotel', 'Home', 'Store', 'ShoppingCart',
  'CreditCard', 'DollarSign', 'Euro', 'PoundSterling', 'Yen',
  'Bitcoin', 'TrendingUp', 'TrendingDown', 'BarChart', 'LineChart',
  'PieChart', 'Activity', 'Target', 'Flag', 'Tag', 'Bookmark',
  'Folder', 'File', 'Archive', 'Inbox', 'Send', 'Inbox',
  'MessageSquare', 'MessageCircle', 'MessageCircleMore', 'PhoneCall',
  'Video', 'Voicemail', 'AtSign', 'Hash', 'Link', 'ExternalLink',
  'Unlink', 'Code', 'Terminal', 'Command', 'Slash', 'Brackets',
  'Braces', 'Parentheses', 'Percent', 'Infinity', 'Pi', 'Sigma',
  'Omega', 'Alpha', 'Beta', 'Gamma', 'Delta', 'Theta', 'Lambda',
  'Mu', 'Nu', 'Xi', 'Omicron', 'Rho', 'Tau', 'Upsilon', 'Phi',
  'Chi', 'Psi'
];

interface IconPickerProps {
  value?: string;
  onChange: (iconName: string) => void;
  label?: string;
}

const IconPicker: React.FC<IconPickerProps> = ({ value, onChange, label = 'Icon' }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // Normalize value - ensure it's never an empty string, use a default if needed
  const normalizedValue = value && value.trim() ? value : undefined;
  
  const allIcons = useMemo(() => {
    const icons: string[] = [];
    const excludedNames = new Set([
      'createLucideIcon',
      'Icon',
      'default',
      'lucideReact',
      'lucide',
      'createElement',
      'Fragment',
      'forwardRef',
      'memo'
    ]);
    
    try {
      // Check if LucideIcons is available
      if (!LucideIcons || typeof LucideIcons !== 'object') {
        console.error('IconPicker: LucideIcons is not available');
        // Return popular icons as fallback
        return popularIcons.filter(icon => icon);
      }
      
      for (const iconName in LucideIcons) {
        // Skip if excluded
        if (excludedNames.has(iconName)) {
          continue;
        }
        
        // Skip if starts with underscore
        if (iconName.startsWith('_')) {
          continue;
        }
        
        // Skip if empty or doesn't start with uppercase letter
        if (!iconName || iconName.length === 0) {
          continue;
        }
        
        // Check if first character is uppercase letter
        const firstChar = iconName.charAt(0);
        if (firstChar < 'A' || firstChar > 'Z') {
          continue;
        }
        
        const iconComponent = (LucideIcons as Record<string, React.ComponentType<{ className?: string }>>)[iconName];
        
        // Only include if it's a function (React component)
        if (typeof iconComponent === 'function') {
          icons.push(iconName);
        }
      }
      
      // If no icons found, use popular icons as fallback
      if (icons.length === 0) {
        console.warn('IconPicker: No icons found, using popular icons as fallback');
        return popularIcons.filter(icon => icon);
      }
      
      const sorted = icons.sort();
      return sorted;
    } catch (error) {
      console.error('IconPicker: Error loading icons:', error);
      // Return popular icons as fallback
      return popularIcons.filter(icon => icon);
    }
  }, []);

  
  const filteredIcons = useMemo(() => {
    if (!searchQuery.trim()) {
      
      const popular = popularIcons.filter(icon => allIcons.includes(icon));
      const others = allIcons.filter(icon => !popularIcons.includes(icon));
      return [...popular, ...others];
    }
    return allIcons.filter((icon) =>
      icon.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [searchQuery, allIcons]);

  const selectedIcon = normalizedValue && (LucideIcons as Record<string, React.ComponentType<{ className?: string }>>)[normalizedValue] ? (LucideIcons as Record<string, React.ComponentType<{ className?: string }>>)[normalizedValue] : null;

  const handleIconSelect = (iconName: string) => {
    onChange(iconName);
    setIsOpen(false);
    setSearchQuery('');
  };

  return (
    <div className="relative">
      <label className="block text-sm font-semibold text-gray-700 mb-2">{label}</label>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-4 py-2 border-2 border-gray-200 rounded-lg bg-white hover:border-purple-400 focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 flex items-center justify-between"
      >
        <div className="flex items-center gap-3">
          {selectedIcon ? (
            <>
              {React.createElement(selectedIcon, { className: 'w-5 h-5 text-gray-700' })}
              <span className="text-gray-700 font-medium">{normalizedValue}</span>
            </>
          ) : (
            <span className="text-gray-400">Select an icon</span>
          )}
        </div>
        <Search className="w-4 h-4 text-gray-400" />
      </button>

      {isOpen && (
        <>
          <div
            className="fixed inset-0 z-[9998]"
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute z-[9999] mt-2 w-full bg-white border-2 border-gray-200 rounded-xl shadow-2xl max-h-96 overflow-hidden flex flex-col">
            <div className="p-4 border-b border-gray-200 sticky top-0 bg-white z-10">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search icons..."
                  className="w-full pl-10 pr-4 py-2 border-2 border-gray-200 rounded-lg focus:border-purple-400 focus:ring-4 focus:ring-purple-100 outline-none"
                  autoFocus
                />
                {searchQuery && (
                  <button
                    type="button"
                    onClick={() => setSearchQuery('')}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
            <div className="overflow-y-auto p-4">
              {allIcons.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <p className="text-sm">Unable to load icons. Please refresh the page.</p>
                  <p className="text-xs mt-2">If the problem persists, check the browser console for errors.</p>
                </div>
              ) : filteredIcons.length > 0 ? (
                <>
                  {!searchQuery.trim() && (
                    <div className="mb-3">
                      <p className="text-sm text-gray-600">
                        Showing {filteredIcons.length} icons. Popular icons appear first.
                      </p>
                    </div>
                  )}
                  <div className="grid grid-cols-6 sm:grid-cols-8 md:grid-cols-10 gap-2">
                    {filteredIcons.slice(0, searchQuery.trim() ? 500 : 300).map((iconName) => {
                      const IconComponent = (LucideIcons as Record<string, React.ComponentType<{ className?: string }>>)[iconName];
                      if (!IconComponent) return null;

                      const isSelected = normalizedValue === iconName;
                      const isPopular = !searchQuery.trim() && popularIcons.includes(iconName);

                      try {
                        return (
                          <button
                            key={iconName}
                            type="button"
                            onClick={() => handleIconSelect(iconName)}
                            className={`
                              p-3 rounded-lg border-2 transition-all duration-200
                              flex items-center justify-center relative
                              ${
                                isSelected
                                  ? 'border-purple-500 bg-purple-50 text-purple-600'
                                  : isPopular
                                  ? 'border-amber-200 hover:border-amber-300 hover:bg-amber-50 text-gray-700'
                                  : 'border-gray-200 hover:border-purple-300 hover:bg-purple-50 text-gray-700'
                              }
                            `}
                            title={iconName}
                          >
                            {React.createElement(IconComponent, { className: 'w-5 h-5' })}
                            {isPopular && !isSelected && (
                              <span className="absolute top-0 right-0 w-2 h-2 bg-amber-400 rounded-full"></span>
                            )}
                          </button>
                        );
                      } catch (error) {
                        console.warn(`Failed to render icon: ${iconName}`, error);
                        return null;
                      }
                    })}
                  </div>
                  {filteredIcons.length > (searchQuery.trim() ? 500 : 300) && (
                    <div className="text-center mt-4 text-sm text-gray-500">
                      Showing first {searchQuery.trim() ? 500 : 300} of {filteredIcons.length} icons. {!searchQuery.trim() && 'Use search to find more.'}
                    </div>
                  )}
                </>
              ) : (
                <div className="text-center py-8 text-gray-500">
                  {searchQuery.trim() ? (
                    <>
                      <p>No icons found matching "{searchQuery}"</p>
                      <p className="text-xs mt-2">Try a different search term</p>
                    </>
                  ) : (
                    <p className="text-sm">No icons available</p>
                  )}
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default IconPicker;

