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

/**
 * 类别过滤器选择器组件
 * 遵循 promptx/frontend-developer 标准的UI/UX优化
 */

interface CategoryFilterSelectorProps {
  selectedCategories: string[];
  availableCategories: string[];
  onCategoriesChange: (categories: string[]) => void;
  maxSelections?: number;
  allowCustom?: boolean;
  placeholder?: string;
  className?: string;
}

export const CategoryFilterSelector: React.FC<CategoryFilterSelectorProps> = ({
  selectedCategories,
  availableCategories,
  onCategoriesChange,
  maxSelections = 5,
  allowCustom = true,
  placeholder = "搜索或添加类别...",
  className = '',
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [showCustomInput, setShowCustomInput] = useState(false);
  const [customCategory, setCustomCategory] = useState('');

  // 过滤可用类别
  const filteredCategories = availableCategories.filter(category =>
    category.toLowerCase().includes(searchQuery.toLowerCase()) &&
    !selectedCategories.includes(category)
  );

  // 处理类别选择
  const handleCategorySelect = useCallback((category: string) => {
    if (selectedCategories.includes(category)) {
      // 取消选择
      onCategoriesChange(selectedCategories.filter(c => c !== category));
    } else if (selectedCategories.length < maxSelections) {
      // 添加选择
      onCategoriesChange([...selectedCategories, category]);
    }
  }, [selectedCategories, onCategoriesChange, maxSelections]);

  // 处理自定义类别添加
  const handleCustomCategoryAdd = useCallback(() => {
    const trimmedCategory = customCategory.trim();
    if (trimmedCategory && 
        !selectedCategories.includes(trimmedCategory) && 
        selectedCategories.length < maxSelections) {
      onCategoriesChange([...selectedCategories, trimmedCategory]);
      setCustomCategory('');
      setShowCustomInput(false);
    }
  }, [customCategory, selectedCategories, onCategoriesChange, maxSelections]);

  // 处理移除选中类别
  const handleRemoveCategory = useCallback((category: string) => {
    onCategoriesChange(selectedCategories.filter(c => c !== category));
  }, [selectedCategories, onCategoriesChange]);

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 已选择的类别 */}
      {selectedCategories.length > 0 && (
        <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) => (
              <div
                key={category}
                className="inline-flex items-center gap-2 px-3 py-1.5 bg-primary-100 text-primary-700 rounded-full text-sm font-medium animate-fade-in"
              >
                <span>{category}</span>
                <button
                  onClick={() => handleRemoveCategory(category)}
                  className="hover:bg-primary-200 rounded-full p-0.5 transition-colors duration-150"
                  aria-label={`移除 ${category}`}
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            ))}
          </div>
          
          {selectedCategories.length >= maxSelections && (
            <p className="text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded">
              最多只能选择 {maxSelections} 个类别
            </p>
          )}
        </div>
      )}

      {/* 搜索框 */}
      <div className="space-y-2">
        <h4 className="text-sm font-medium text-gray-700">选择类别</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={placeholder}
            className="form-input pl-10 pr-4"
          />
        </div>
      </div>

      {/* 可选类别列表 */}
      <div className="space-y-2">
        <div className="max-h-48 overflow-y-auto space-y-1">
          {filteredCategories.map((category) => (
            <button
              key={category}
              onClick={() => handleCategorySelect(category)}
              disabled={selectedCategories.length >= maxSelections}
              className={`w-full flex items-center justify-between px-3 py-2 text-left rounded-lg transition-all duration-150 ${
                selectedCategories.length >= maxSelections
                  ? 'bg-gray-50 text-gray-400 cursor-not-allowed'
                  : 'bg-white hover:bg-gray-50 border border-gray-200 hover:border-primary-300 hover-lift'
              }`}
            >
              <span className="text-sm">{category}</span>
              <Plus className="w-4 h-4 text-gray-400" />
            </button>
          ))}
          
          {filteredCategories.length === 0 && searchQuery && (
            <div className="text-center py-4 text-gray-500">
              <p className="text-sm">未找到匹配的类别</p>
              {allowCustom && selectedCategories.length < maxSelections && (
                <button
                  onClick={() => {
                    setCustomCategory(searchQuery);
                    setShowCustomInput(true);
                  }}
                  className="text-primary-600 hover:text-primary-700 text-sm mt-1"
                >
                  添加 "{searchQuery}" 为自定义类别
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 自定义类别输入 */}
      {allowCustom && selectedCategories.length < maxSelections && (
        <div className="space-y-2">
          {!showCustomInput ? (
            <button
              onClick={() => setShowCustomInput(true)}
              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={customCategory}
                onChange={(e) => setCustomCategory(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleCustomCategoryAdd();
                  } else if (e.key === 'Escape') {
                    setShowCustomInput(false);
                    setCustomCategory('');
                  }
                }}
                placeholder="输入自定义类别名称"
                className="flex-1 form-input"
                autoFocus
              />
              <button
                onClick={handleCustomCategoryAdd}
                disabled={!customCategory.trim()}
                className="btn btn-primary btn-sm"
              >
                <Check className="w-4 h-4" />
              </button>
              <button
                onClick={() => {
                  setShowCustomInput(false);
                  setCustomCategory('');
                }}
                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>
  );
};
