import React, { useState, useCallback } from 'react';
import { Palette, Plus, X, Search, Sparkles } from 'lucide-react';

/**
 * 设计风格选择器组件
 * 遵循 promptx/frontend-developer 标准的UI/UX优化
 */

interface DesignStyleSelectorProps {
  selectedCategories: string[];
  designStyles: Record<string, string[]>;
  availableStyles: string[];
  onDesignStylesChange: (category: string, styles: string[]) => void;
  maxStylesPerCategory?: number;
  allowCustom?: boolean;
  className?: string;
}

export const DesignStyleSelector: React.FC<DesignStyleSelectorProps> = ({
  selectedCategories,
  designStyles,
  availableStyles,
  onDesignStylesChange,
  maxStylesPerCategory = 3,
  allowCustom = true,
  className = '',
}) => {
  const [activeCategory, setActiveCategory] = useState<string>(selectedCategories[0] || '');
  const [searchQuery, setSearchQuery] = useState('');
  const [showCustomInput, setShowCustomInput] = useState<string | null>(null);
  const [customStyle, setCustomStyle] = useState('');

  // 过滤可用风格
  const getFilteredStyles = useCallback((category: string) => {
    const categoryStyles = designStyles[category] || [];
    return availableStyles.filter(style =>
      style.toLowerCase().includes(searchQuery.toLowerCase()) &&
      !categoryStyles.includes(style)
    );
  }, [searchQuery, designStyles, availableStyles]);

  // 处理风格选择
  const handleStyleSelect = useCallback((category: string, style: string) => {
    const currentStyles = designStyles[category] || [];
    if (currentStyles.includes(style)) {
      // 移除风格
      onDesignStylesChange(category, currentStyles.filter(s => s !== style));
    } else if (currentStyles.length < maxStylesPerCategory) {
      // 添加风格
      onDesignStylesChange(category, [...currentStyles, style]);
    }
  }, [designStyles, onDesignStylesChange, maxStylesPerCategory]);

  // 处理自定义风格添加
  const handleCustomStyleAdd = useCallback((category: string) => {
    const trimmedStyle = customStyle.trim();
    const currentStyles = designStyles[category] || [];
    
    if (trimmedStyle && 
        !currentStyles.includes(trimmedStyle) && 
        currentStyles.length < maxStylesPerCategory) {
      onDesignStylesChange(category, [...currentStyles, trimmedStyle]);
      setCustomStyle('');
      setShowCustomInput(null);
    }
  }, [customStyle, designStyles, onDesignStylesChange, maxStylesPerCategory]);

  // 处理移除风格
  const handleRemoveStyle = useCallback((category: string, style: string) => {
    const currentStyles = designStyles[category] || [];
    onDesignStylesChange(category, currentStyles.filter(s => s !== style));
  }, [designStyles, onDesignStylesChange]);

  // 风格颜色映射
  const getStyleColor = (style: string) => {
    const colorMap: Record<string, string> = {
      '休闲': 'bg-blue-100 text-blue-700 border-blue-300',
      '正式': 'bg-gray-100 text-gray-700 border-gray-300',
      '运动': 'bg-orange-100 text-orange-700 border-orange-300',
      '街头': 'bg-purple-100 text-purple-700 border-purple-300',
      '简约': 'bg-green-100 text-green-700 border-green-300',
      '复古': 'bg-amber-100 text-amber-700 border-amber-300',
      '时尚': 'bg-pink-100 text-pink-700 border-pink-300',
      '优雅': 'bg-indigo-100 text-indigo-700 border-indigo-300',
    };
    return colorMap[style] || 'bg-gray-100 text-gray-700 border-gray-300';
  };

  if (selectedCategories.length === 0) {
    return (
      <div className={`text-center py-8 ${className}`}>
        <Palette className="w-12 h-12 text-gray-400 mx-auto mb-3" />
        <h4 className="text-sm font-medium text-gray-600 mb-2">需要先选择类别</h4>
        <p className="text-xs text-gray-500">
          请在"类别"标签页中选择至少一个类别，然后为每个类别设置设计风格
        </p>
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 类别选择器 */}
      {selectedCategories.length > 1 && (
        <div className="space-y-2">
          <h4 className="text-sm font-medium text-gray-700">选择类别</h4>
          <div className="flex flex-wrap gap-2">
            {selectedCategories.map((category) => (
              <button
                key={category}
                onClick={() => setActiveCategory(category)}
                className={`px-3 py-1.5 rounded-full text-sm font-medium transition-all duration-200 ${
                  activeCategory === category
                    ? 'bg-primary-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                {category}
                {designStyles[category]?.length > 0 && (
                  <span className="ml-1 text-xs">({designStyles[category].length})</span>
                )}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 当前类别的已选风格 */}
      {activeCategory && designStyles[activeCategory]?.length > 0 && (
        <div className="space-y-2">
          <h4 className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <Sparkles className="w-4 h-4" />
            {activeCategory} 的设计风格
          </h4>
          <div className="flex flex-wrap gap-2">
            {designStyles[activeCategory].map((style) => (
              <div
                key={style}
                className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium border animate-fade-in ${getStyleColor(style)}`}
              >
                <span>{style}</span>
                <button
                  onClick={() => handleRemoveStyle(activeCategory, style)}
                  className="hover:bg-black hover:bg-opacity-10 rounded-full p-0.5 transition-colors duration-150"
                  aria-label={`移除 ${style}`}
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            ))}
          </div>
          
          {designStyles[activeCategory].length >= maxStylesPerCategory && (
            <p className="text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded">
              每个类别最多只能选择 {maxStylesPerCategory} 个设计风格
            </p>
          )}
        </div>
      )}

      {/* 搜索框 */}
      <div className="space-y-2">
        <h4 className="text-sm font-medium text-gray-700">
          为 "{activeCategory}" 添加设计风格
        </h4>
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="搜索设计风格..."
            className="form-input pl-10 pr-4"
          />
        </div>
      </div>

      {/* 可选风格列表 */}
      {activeCategory && (
        <div className="space-y-2">
          <div className="grid grid-cols-2 gap-2 max-h-48 overflow-y-auto">
            {getFilteredStyles(activeCategory).map((style) => {
              const currentStyles = designStyles[activeCategory] || [];
              const isDisabled = currentStyles.length >= maxStylesPerCategory;
              
              return (
                <button
                  key={style}
                  onClick={() => handleStyleSelect(activeCategory, style)}
                  disabled={isDisabled}
                  className={`flex items-center justify-between px-3 py-2 text-left rounded-lg transition-all duration-150 ${
                    isDisabled
                      ? 'bg-gray-50 text-gray-400 cursor-not-allowed'
                      : `bg-white hover:bg-gray-50 border border-gray-200 hover-lift ${getStyleColor(style).replace('bg-', 'hover:bg-').replace('100', '50')}`
                  }`}
                >
                  <span className="text-sm">{style}</span>
                  <Plus className="w-4 h-4 text-gray-400" />
                </button>
              );
            })}
          </div>
          
          {getFilteredStyles(activeCategory).length === 0 && searchQuery && (
            <div className="text-center py-4 text-gray-500">
              <p className="text-sm">未找到匹配的设计风格</p>
              {allowCustom && (designStyles[activeCategory]?.length || 0) < maxStylesPerCategory && (
                <button
                  onClick={() => {
                    setCustomStyle(searchQuery);
                    setShowCustomInput(activeCategory);
                  }}
                  className="text-primary-600 hover:text-primary-700 text-sm mt-1"
                >
                  添加 "{searchQuery}" 为自定义风格
                </button>
              )}
            </div>
          )}
        </div>
      )}

      {/* 自定义风格输入 */}
      {allowCustom && activeCategory && (designStyles[activeCategory]?.length || 0) < maxStylesPerCategory && (
        <div className="space-y-2">
          {showCustomInput !== activeCategory ? (
            <button
              onClick={() => setShowCustomInput(activeCategory)}
              className="w-full flex items-center justify-center gap-2 px-3 py-2 border-2 border-dashed border-gray-300 rounded-lg text-gray-600 hover:border-primary-400 hover:text-primary-600 transition-all duration-200"
            >
              <Plus className="w-4 h-4" />
              <span className="text-sm">添加自定义设计风格</span>
            </button>
          ) : (
            <div className="flex gap-2">
              <input
                type="text"
                value={customStyle}
                onChange={(e) => setCustomStyle(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleCustomStyleAdd(activeCategory);
                  } else if (e.key === 'Escape') {
                    setShowCustomInput(null);
                    setCustomStyle('');
                  }
                }}
                placeholder="输入自定义设计风格"
                className="flex-1 form-input"
                autoFocus
              />
              <button
                onClick={() => handleCustomStyleAdd(activeCategory)}
                disabled={!customStyle.trim()}
                className="btn btn-primary btn-sm"
              >
                <Plus className="w-4 h-4" />
              </button>
              <button
                onClick={() => {
                  setShowCustomInput(null);
                  setCustomStyle('');
                }}
                className="btn btn-ghost btn-sm"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      )}

      {/* 使用提示 */}
      <div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
        <p>🎨 提示：设计风格帮助匹配特定审美偏好的搭配方案</p>
      </div>
    </div>
  );
};
