import React, { useState, useCallback } from 'react';
import { open } from '@tauri-apps/plugin-dialog';
import {
  FilterPanelProps,
  ColorFilter,
  DEFAULT_COLOR_FILTER,
  COMMON_CATEGORIES,
  COMMON_ENVIRONMENTS,
  COMMON_DESIGN_STYLES,
  SUPPORTED_IMAGE_FORMATS
} from '../../types/outfitSearch';
import { ColorPicker } from './ColorPicker';
import { ColorUtils } from '../../utils/colorUtils';
import { Upload, Image as ImageIcon, X, Sparkles, AlertCircle, Tags } from 'lucide-react';
import { convertFileSrc } from '@tauri-apps/api/core';
import { CustomTagSelector } from '../CustomTagSelector';

/**
 * 高级过滤面板组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const FilterPanel: React.FC<FilterPanelProps> = ({
  config,
  onConfigChange,
  analysisResult,
  onImageSelect,
  onAnalyzeImage,
  selectedImage,
  isAnalyzing = false,
  analysisError,
}) => {
  const [activeColorCategory, setActiveColorCategory] = useState<string | null>(null);
  const [dragOver, setDragOver] = useState(false);
  const [localError, setLocalError] = useState<string | null>(null);
  const [selectedCustomTags, setSelectedCustomTags] = useState<string[]>([]);

  // 从分析结果中提取动态选项
  const getDynamicOptions = useCallback(() => {
    const options = {
      categories: [...COMMON_CATEGORIES],
      environments: [...COMMON_ENVIRONMENTS],
      designStyles: [...COMMON_DESIGN_STYLES],
    };

    if (analysisResult) {
      // 添加分析结果中的类别
      console.log(analysisResult)
      if (analysisResult.products && analysisResult.products.length > 0) {
        const analysisCategories = analysisResult.products.map(p => p.category);
        options.categories = [...new Set([...options.categories, ...analysisCategories])];

        // 添加分析结果中的设计风格
        const analysisStyles = analysisResult.products.flatMap(p => p.design_styles || []);
        options.designStyles = [...new Set([...options.designStyles, ...analysisStyles])];
      }

      // 添加分析结果中的环境标签
      if (analysisResult.environment_tags && analysisResult.environment_tags.length > 0) {
        const validEnvTags = analysisResult.environment_tags.filter(tag => tag !== 'Unknown');
        options.environments = [...new Set([...options.environments, ...validEnvTags])];
      }
    }

    return options;
  }, [analysisResult]);

  // 处理文件选择
  const handleFileSelect = useCallback(async () => {
    if (!onImageSelect) return;

    try {
      const selected = await open({
        multiple: false,
        filters: [
          {
            name: '图像文件',
            extensions: SUPPORTED_IMAGE_FORMATS,
          },
        ],
      });

      if (selected && typeof selected === 'string') {
        setLocalError(null);
        onImageSelect(selected);
      }
    } catch (error) {
      console.error('Failed to select file:', error);
      setLocalError('文件选择失败');
    }
  }, [onImageSelect]);

  // 处理拖拽
  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOver(false);

    if (!onImageSelect) return;

    const files = Array.from(e.dataTransfer.files);
    if (files.length === 0) return;

    const file = files[0];
    const extension = file.name.split('.').pop()?.toLowerCase();

    if (!extension || !SUPPORTED_IMAGE_FORMATS.includes(extension)) {
      setLocalError(`不支持的文件格式。支持的格式：${SUPPORTED_IMAGE_FORMATS.join(', ')}`);
      return;
    }

    setLocalError(null);
    onImageSelect(file.name);
  }, [onImageSelect]);

  // 执行图像分析
  const handleAnalyze = useCallback(() => {
    if (!selectedImage || !onAnalyzeImage) return;

    setLocalError(null);
    onAnalyzeImage(selectedImage);
  }, [selectedImage, onAnalyzeImage]);

  // 清除选择的图像
  const handleClearImage = useCallback(() => {
    if (!onImageSelect) return;
    onImageSelect(null);
    setLocalError(null);
  }, [onImageSelect]);

  // 处理类别选择
  const handleCategoryToggle = useCallback((category: string) => {
    const newCategories = config.categories.includes(category)
      ? config.categories.filter(c => c !== category)
      : [...config.categories, category];

    onConfigChange({
      ...config,
      categories: newCategories,
    });
  }, [config, onConfigChange]);

  // 处理环境标签选择
  const handleEnvironmentToggle = useCallback((environment: string) => {
    const newEnvironments = config.environments.includes(environment)
      ? config.environments.filter(e => e !== environment)
      : [...config.environments, environment];

    onConfigChange({
      ...config,
      environments: newEnvironments,
    });
  }, [config, onConfigChange]);

  // 处理设计风格选择
  const handleDesignStyleToggle = useCallback((category: string, style: string) => {
    const currentStyles = config.design_styles[category] || [];
    const newStyles = currentStyles.includes(style)
      ? currentStyles.filter(s => s !== style)
      : [...currentStyles, style];

    onConfigChange({
      ...config,
      design_styles: {
        ...config.design_styles,
        [category]: newStyles,
      },
    });
  }, [config, onConfigChange]);

  // 处理颜色过滤器启用/禁用
  const handleColorFilterToggle = useCallback((category: string) => {
    const currentFilter = config.color_filters[category] || DEFAULT_COLOR_FILTER;
    const newFilter: ColorFilter = {
      ...currentFilter,
      enabled: !currentFilter.enabled,
    };

    onConfigChange({
      ...config,
      color_filters: {
        ...config.color_filters,
        [category]: newFilter,
      },
    });
  }, [config, onConfigChange]);

  // 处理颜色变化
  const handleColorChange = useCallback((category: string, color: any) => {
    const currentFilter = config.color_filters[category] || DEFAULT_COLOR_FILTER;
    const newFilter: ColorFilter = {
      ...currentFilter,
      color,
    };

    onConfigChange({
      ...config,
      color_filters: {
        ...config.color_filters,
        [category]: newFilter,
      },
    });
  }, [config, onConfigChange]);

  // 处理阈值变化
  const handleThresholdChange = useCallback((
    category: string,
    field: 'hue_threshold' | 'saturation_threshold' | 'value_threshold',
    value: number
  ) => {
    const currentFilter = config.color_filters[category] || DEFAULT_COLOR_FILTER;
    const newFilter: ColorFilter = {
      ...currentFilter,
      [field]: value,
    };

    onConfigChange({
      ...config,
      color_filters: {
        ...config.color_filters,
        [category]: newFilter,
      },
    });
  }, [config, onConfigChange]);

  // 清除所有筛选
  const handleClearFilters = useCallback(() => {
    onConfigChange({
      ...config,
      categories: [],
      environments: [],
      color_filters: {},
      design_styles: {},
    });
  }, [config, onConfigChange]);

  // 获取动态选项
  const dynamicOptions = getDynamicOptions();

  // 检查是否有活动筛选
  const hasActiveFilters = config.categories.length > 0 ||
    config.environments.length > 0 ||
    Object.values(config.color_filters).some(f => f.enabled) ||
    Object.values(config.design_styles).some(styles => styles.length > 0);

  return (
    <div className="filter-panel">
      <div className="filter-header">
        <h3 className="filter-title">高级筛选</h3>
        {hasActiveFilters && (
          <button onClick={handleClearFilters} className="clear-filters-button">
            清除筛选
          </button>
        )}
      </div>

      {/* 图片分析区域 */}
      {onImageSelect && (
        <div className="image-analysis-section">
          <h4 className="section-title">
            <ImageIcon className="w-4 h-4 mr-2" />
            图片智能分析
          </h4>

          {!selectedImage ? (
            <div
              className={`image-upload-area ${dragOver ? 'drag-over' : ''}`}
              onDragEnter={handleDragEnter}
              onDragLeave={handleDragLeave}
              onDragOver={handleDragOver}
              onDrop={handleDrop}
              onClick={handleFileSelect}
            >
              <div className="upload-content">
                <div className={`upload-icon ${dragOver ? 'drag-active' : ''}`}>
                  <Upload className="w-6 h-6" />
                </div>
                <div className="upload-text">
                  <p className="upload-primary">点击或拖拽图片到此处</p>
                  <p className="upload-secondary">AI将自动分析并生成筛选条件</p>
                </div>
              </div>
            </div>
          ) : (
            <div className="selected-image-area">
              <div className="image-preview-container">
                <img
                  src={convertFileSrc(selectedImage)}
                  alt="Selected outfit"
                  className="image-preview"
                  onError={() => setLocalError('图片加载失败')}
                />
                <button
                  onClick={handleClearImage}
                  className="remove-image-button"
                  disabled={isAnalyzing}
                  title="移除图片"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              <div className="analysis-controls">
                <button
                  onClick={handleAnalyze}
                  disabled={isAnalyzing}
                  className="analyze-button"
                >
                  {isAnalyzing ? (
                    <>
                      <div className="spinner" />
                      AI分析中...
                    </>
                  ) : (
                    <>
                      <Sparkles className="w-4 h-4" />
                      开始AI分析
                    </>
                  )}
                </button>

                {(analysisError || localError) && (
                  <div className="error-message">
                    <AlertCircle className="w-4 h-4" />
                    {analysisError || localError}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      )}

      {/* 类别筛选 */}
      <div className="filter-section">
        <h4 className="section-title">
          服装类别
          {analysisResult && analysisResult.products && analysisResult.products.length > 0 && (
            <span className="dynamic-indicator">（包含AI识别类别）</span>
          )}
        </h4>
        <div className="filter-tags">
          {dynamicOptions.categories.map((category) => {
            const isFromAnalysis = analysisResult?.products?.some(p => p.category === category);
            return (
              <button
                key={category}
                onClick={() => handleCategoryToggle(category)}
                className={`filter-tag ${config.categories.includes(category) ? 'active' : ''} ${isFromAnalysis ? 'from-analysis' : ''}`}
                title={isFromAnalysis ? '来自AI分析结果' : '常用类别'}
              >
                {category}
                {isFromAnalysis && <span className="analysis-star">✨</span>}
              </button>
            );
          })}
        </div>
      </div>

      {/* 环境标签筛选 */}
      <div className="filter-section">
        <h4 className="section-title">
          环境场景
          {analysisResult && analysisResult.environment_tags && analysisResult.environment_tags.length > 0 && (
            <span className="dynamic-indicator">（包含AI识别场景）</span>
          )}
        </h4>
        <div className="filter-tags">
          {dynamicOptions.environments.map((environment) => {
            const isFromAnalysis = analysisResult?.environment_tags?.includes(environment);
            return (
              <button
                key={environment}
                onClick={() => handleEnvironmentToggle(environment)}
                className={`filter-tag ${config.environments.includes(environment) ? 'active' : ''} ${isFromAnalysis ? 'from-analysis' : ''}`}
                title={isFromAnalysis ? '来自AI分析结果' : '常用环境'}
              >
                {environment}
                {isFromAnalysis && <span className="analysis-star">✨</span>}
              </button>
            );
          })}
        </div>
      </div>

      {/* 商品筛选 - 颜色匹配 + 设计风格 */}
      <div className="filter-section">
        <h4 className="section-title">
          风格及颜色
          {analysisResult && analysisResult.products && analysisResult.products.length > 0 && (
            <span className="dynamic-indicator">（基于AI识别商品）</span>
          )}
        </h4>

        {analysisResult && analysisResult.products && analysisResult.products.length > 0 ? (
          // 显示AI识别的商品，包含颜色和设计风格
          <div className="product-filters">
            {analysisResult.products.map((product, index) => {
              const productKey = `${product.category}_${index}`;
              const colorFilter = config.color_filters[productKey] || {
                ...DEFAULT_COLOR_FILTER,
                color: product.color_pattern || DEFAULT_COLOR_FILTER.color,
              };
              const selectedStyles = config.design_styles[productKey] || [];
              const isColorActive = activeColorCategory === productKey;

              return (
                <div key={productKey} className="product-filter-item">
                  {/* 商品标题和描述 */}
                  <div className="product-header">
                    <h5 className="product-title">
                      <span className="product-label from-analysis">
                        {product.category}
                        <span className="analysis-star">✨</span>
                      </span>
                    </h5>
                    <div className="product-description-mini">
                      {product.description}
                    </div>
                  </div>

                  {/* 颜色筛选 */}
                  <div className="product-color-section">
                    <div className="color-filter-header">
                      <label className="color-filter-label">
                        <input
                          type="checkbox"
                          checked={colorFilter.enabled}
                          onChange={() => handleColorFilterToggle(productKey)}
                          className="color-filter-checkbox"
                        />
                        <span className="filter-section-label">颜色匹配</span>
                      </label>

                      {colorFilter.enabled && (
                        <div className="color-preview-container">
                          <div
                            className="color-preview-small"
                            style={{ backgroundColor: ColorUtils.hsvToHex(colorFilter.color) }}
                            onClick={() => setActiveColorCategory(isColorActive ? null : productKey)}
                            title="点击编辑颜色"
                          />
                          <button
                            onClick={() => setActiveColorCategory(isColorActive ? null : productKey)}
                            className="color-edit-button"
                          >
                            {isColorActive ? '收起' : '纠正颜色'}
                          </button>
                        </div>
                      )}
                    </div>

                    {colorFilter.enabled && isColorActive && (
                      <div className="color-picker-container">
                        <div className="color-picker-header">
                          <h6>调整 {product.category} 的颜色匹配</h6>
                          <p className="color-hint">拖动色盘选择更准确的颜色，或调整容差范围</p>
                        </div>

                        <ColorPicker
                          color={colorFilter.color}
                          onChange={(color) => handleColorChange(productKey, color)}
                        />

                        <div className="threshold-controls">
                          <div className="threshold-control">
                            <label>色相容差</label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={colorFilter.hue_threshold}
                              onChange={(e) => handleThresholdChange(productKey, 'hue_threshold', parseFloat(e.target.value))}
                              className="threshold-slider"
                            />
                            <span className="threshold-value">{colorFilter.hue_threshold.toFixed(2)}</span>
                          </div>

                          <div className="threshold-control">
                            <label>饱和度容差</label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={colorFilter.saturation_threshold}
                              onChange={(e) => handleThresholdChange(productKey, 'saturation_threshold', parseFloat(e.target.value))}
                              className="threshold-slider"
                            />
                            <span className="threshold-value">{colorFilter.saturation_threshold.toFixed(2)}</span>
                          </div>

                          <div className="threshold-control">
                            <label>明度容差</label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={colorFilter.value_threshold}
                              onChange={(e) => handleThresholdChange(productKey, 'value_threshold', parseFloat(e.target.value))}
                              className="threshold-slider"
                            />
                            <span className="threshold-value">{colorFilter.value_threshold.toFixed(2)}</span>
                          </div>
                        </div>

                        <div className="color-actions">
                          <button
                            onClick={() => {
                              // 重置为AI识别的原始颜色
                              if (product.color_pattern) {
                                handleColorChange(productKey, product.color_pattern);
                              }
                            }}
                            className="reset-color-button"
                          >
                            重置为AI识别颜色
                          </button>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* 设计风格筛选 */}
                  {product.design_styles && product.design_styles.length > 0 && (
                    <div className="product-style-section">
                      <h6 className="filter-section-label">设计风格</h6>
                      <div className="filter-tags">
                        {product.design_styles.map((style) => {
                          const isSelected = selectedStyles.includes(style);
                          return (
                            <button
                              key={style}
                              onClick={() => handleDesignStyleToggle(productKey, style)}
                              className={`filter-tag ${isSelected ? 'active' : ''} from-analysis style-tag`}
                              title="来自AI分析的设计风格"
                            >
                              {style}
                              <span className="analysis-star">✨</span>
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ) : (
          // 如果没有AI识别结果，显示传统的分离式筛选
          <div className="traditional-filters">
            {/* 传统颜色筛选 */}
            {config.categories.length > 0 ? (
              <div className="traditional-color-section">
                <h6 className="filter-section-label">颜色匹配</h6>
                {config.categories.map((category) => {
                  const colorFilter = config.color_filters[category] || DEFAULT_COLOR_FILTER;
                  const isActive = activeColorCategory === category;

                  return (
                    <div key={category} className="color-filter-item">
                      <div className="color-filter-header">
                        <label className="color-filter-label">
                          <input
                            type="checkbox"
                            checked={colorFilter.enabled}
                            onChange={() => handleColorFilterToggle(category)}
                            className="color-filter-checkbox"
                          />
                          {category} 颜色匹配
                        </label>

                        {colorFilter.enabled && (
                          <div className="color-preview-container">
                            <div
                              className="color-preview-small"
                              style={{ backgroundColor: ColorUtils.hsvToHex(colorFilter.color) }}
                              onClick={() => setActiveColorCategory(isActive ? null : category)}
                            />
                            <button
                              onClick={() => setActiveColorCategory(isActive ? null : category)}
                              className="color-edit-button"
                            >
                              {isActive ? '收起' : '编辑'}
                            </button>
                          </div>
                        )}
                      </div>

                      {colorFilter.enabled && isActive && (
                        <div className="color-picker-container">
                          <ColorPicker
                            color={colorFilter.color}
                            onChange={(color) => handleColorChange(category, color)}
                          />

                          <div className="threshold-controls">
                            <div className="threshold-control">
                              <label>色相阈值</label>
                              <input
                                type="range"
                                min="0"
                                max="0.2"
                                step="0.01"
                                value={colorFilter.hue_threshold}
                                onChange={(e) => handleThresholdChange(category, 'hue_threshold', parseFloat(e.target.value))}
                                className="threshold-slider"
                              />
                              <span className="threshold-value">{colorFilter.hue_threshold.toFixed(2)}</span>
                            </div>

                            <div className="threshold-control">
                              <label>饱和度阈值</label>
                              <input
                                type="range"
                                min="0"
                                max="0.2"
                                step="0.01"
                                value={colorFilter.saturation_threshold}
                                onChange={(e) => handleThresholdChange(category, 'saturation_threshold', parseFloat(e.target.value))}
                                className="threshold-slider"
                              />
                              <span className="threshold-value">{colorFilter.saturation_threshold.toFixed(2)}</span>
                            </div>

                            <div className="threshold-control">
                              <label>明度阈值</label>
                              <input
                                type="range"
                                min="0"
                                max="0.5"
                                step="0.01"
                                value={colorFilter.value_threshold}
                                onChange={(e) => handleThresholdChange(category, 'value_threshold', parseFloat(e.target.value))}
                                className="threshold-slider"
                              />
                              <span className="threshold-value">{colorFilter.value_threshold.toFixed(2)}</span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : null}

            {/* 传统设计风格筛选 */}
            {config.categories.length > 0 ? (
              <div className="traditional-style-section">
                <h6 className="filter-section-label">设计风格</h6>
                {config.categories.map((category) => (
                  <div key={category} className="style-category">
                    <h6 className="style-category-title">{category}</h6>
                    <div className="filter-tags">
                      {dynamicOptions.designStyles.map((style) => {
                        const isSelected = (config.design_styles[category] || []).includes(style);
                        return (
                          <button
                            key={style}
                            onClick={() => handleDesignStyleToggle(category, style)}
                            className={`filter-tag ${isSelected ? 'active' : ''}`}
                          >
                            {style}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                ))}
              </div>
            ) : null}

            {config.categories.length === 0 && (
              <div className="no-analysis-hint">
                <p>上传图片进行AI分析，或手动选择服装类别以启用商品筛选</p>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 自定义标签筛选 */}
      <div className="filter-section">
        <h4 className="section-title">
          <Tags className="w-4 h-4 mr-2" />
          自定义标签
        </h4>
        <div className="custom-tag-selector-wrapper">
          <CustomTagSelector
            selectedTagIds={selectedCustomTags}
            onSelectionChange={setSelectedCustomTags}
            multiple={true}
            showCategoryFilter={true}
            showSearch={true}
            allowCreate={true}
            placeholder="选择或创建自定义标签..."
          />
        </div>
        {selectedCustomTags.length > 0 && (
          <div className="selected-tags-info">
            已选择 {selectedCustomTags.length} 个标签
          </div>
        )}
      </div>

      <style>{`
        .filter-panel {
          background: #f9fafb;
          border-radius: 8px;
          padding: 16px;
          margin-top: 16px;
          border: 1px solid #e5e7eb;
        }

        .filter-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
        }

        .filter-title {
          font-size: 16px;
          font-weight: 600;
          color: #374151;
          margin: 0;
        }

        .clear-filters-button {
          padding: 6px 12px;
          background: #ef4444;
          color: white;
          border: none;
          border-radius: 6px;
          font-size: 12px;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .clear-filters-button:hover {
          background: #dc2626;
        }

        .filter-section {
          margin-bottom: 20px;
        }

        .section-title {
          font-size: 14px;
          font-weight: 600;
          color: #374151;
          margin: 0 0 8px 0;
        }

        .filter-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .filter-tag {
          padding: 6px 12px;
          border: 1px solid #e2e8f0;
          border-radius: 16px;
          background: #f8fafc;
          color: #64748b;
          font-size: 12px;
          cursor: pointer;
          transition: all 0.2s ease;
          font-weight: 500;
        }

        .filter-tag:hover {
          background: #f1f5f9;
          border-color: #cbd5e1;
          color: #475569;
          transform: translateY(-1px);
        }

        .filter-tag.active {
          background: #3b82f6;
          color: white;
          border-color: #3b82f6;
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
        }

        .filter-tag.active:hover {
          background: #2563eb;
          border-color: #2563eb;
          transform: translateY(-1px);
        }

        .color-filters {
          space-y: 12px;
        }

        .color-filter-item {
          background: white;
          border-radius: 8px;
          padding: 12px;
          border: 1px solid #e5e7eb;
          margin-bottom: 12px;
        }

        .color-filter-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .color-filter-label {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
        }

        .color-filter-checkbox {
          width: 16px;
          height: 16px;
        }

        .color-preview-container {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .color-preview-small {
          width: 24px;
          height: 24px;
          border-radius: 4px;
          border: 1px solid #e5e7eb;
          cursor: pointer;
        }

        .color-edit-button {
          padding: 4px 8px;
          border: 1px solid #d1d5db;
          border-radius: 4px;
          background: white;
          font-size: 12px;
          cursor: pointer;
        }

        .color-picker-container {
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid #e5e7eb;
        }

        .threshold-controls {
          margin-top: 16px;
          display: grid;
          gap: 12px;
        }

        .threshold-control {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .threshold-control label {
          font-size: 12px;
          font-weight: 500;
          min-width: 80px;
        }

        .threshold-slider {
          flex: 1;
          height: 4px;
          background: #e5e7eb;
          border-radius: 2px;
          outline: none;
          cursor: pointer;
        }

        .threshold-value {
          font-size: 12px;
          font-family: monospace;
          min-width: 40px;
          text-align: right;
        }

        .style-category {
          margin-bottom: 12px;
        }

        .style-category-title {
          font-size: 13px;
          font-weight: 500;
          color: #6b7280;
          margin: 0 0 6px 0;
        }

        .no-categories-hint {
          color: #6b7280;
          font-size: 13px;
          font-style: italic;
          margin: 0;
          text-align: center;
          padding: 20px;
        }

        .analysis-indicator {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .analysis-badge {
          background: #3b82f6;
          color: white;
          font-size: 11px;
          padding: 2px 8px;
          border-radius: 12px;
          font-weight: 500;
          border: 1px solid #2563eb;
        }

        .dynamic-indicator {
          font-size: 11px;
          color: #3b82f6;
          font-weight: 500;
          margin-left: 8px;
        }

        .filter-tag.from-analysis {
          background: #f0f9ff;
          border: 1px solid #bae6fd;
          color: #0369a1;
          position: relative;
        }

        .filter-tag.from-analysis:hover {
          background: #e0f2fe;
          border-color: #7dd3fc;
          color: #0284c7;
          transform: translateY(-1px);
        }

        .filter-tag.from-analysis.active {
          background: #3b82f6;
          border-color: #3b82f6;
          color: white;
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
        }

        .analysis-star {
          font-size: 10px;
          margin-left: 4px;
          opacity: 0.8;
        }

        .filter-tag.from-analysis.active .analysis-star {
          opacity: 1;
        }

        /* 图片分析区域样式 */
        .image-analysis-section {
          margin-bottom: 24px;
          padding: 16px;
          background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
          border: 1px solid #cbd5e1;
          border-radius: 12px;
        }

        .image-upload-area {
          border: 2px dashed #cbd5e1;
          border-radius: 8px;
          padding: 24px;
          text-align: center;
          cursor: pointer;
          transition: all 0.3s ease;
          background: white;
        }

        .image-upload-area:hover {
          border-color: #3b82f6;
          background: #f0f9ff;
        }

        .image-upload-area.drag-over {
          border-color: #3b82f6;
          background: #dbeafe;
          transform: scale(1.02);
        }

        .upload-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 12px;
        }

        .upload-icon {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          background: #f1f5f9;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #64748b;
          transition: all 0.3s ease;
        }

        .upload-icon.drag-active {
          background: #3b82f6;
          color: white;
          transform: scale(1.1);
        }

        .upload-text {
          text-align: center;
        }

        .upload-primary {
          font-size: 14px;
          font-weight: 600;
          color: #334155;
          margin: 0 0 4px 0;
        }

        .upload-secondary {
          font-size: 12px;
          color: #64748b;
          margin: 0;
        }

        .selected-image-area {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .image-preview-container {
          position: relative;
          display: inline-block;
        }

        .image-preview {
          width: 100%;
          max-width: 200px;
          height: 120px;
          object-fit: cover;
          border-radius: 8px;
          border: 1px solid #e2e8f0;
        }

        .remove-image-button {
          position: absolute;
          top: 8px;
          right: 8px;
          width: 24px;
          height: 24px;
          background: rgba(0, 0, 0, 0.7);
          color: white;
          border: none;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .remove-image-button:hover {
          background: #ef4444;
          transform: scale(1.1);
        }

        .remove-image-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .analysis-controls {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .analyze-button {
          background: #3b82f6;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 16px;
          font-size: 14px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
        }

        .analyze-button:hover:not(:disabled) {
          background: #2563eb;
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }

        .analyze-button:disabled {
          opacity: 0.7;
          cursor: not-allowed;
          transform: none;
        }

        .spinner {
          width: 16px;
          height: 16px;
          border: 2px solid rgba(255, 255, 255, 0.3);
          border-top: 2px solid white;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        .error-message {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          background: #fef2f2;
          border: 1px solid #fecaca;
          border-radius: 6px;
          color: #dc2626;
          font-size: 12px;
        }

        @media (max-width: 640px) {
          .image-analysis-section {
            padding: 12px;
          }

          .image-upload-area {
            padding: 16px;
          }

          .upload-icon {
            width: 40px;
            height: 40px;
          }

          .image-preview {
            max-width: 150px;
            height: 90px;
          }
        }

        /* AI商品颜色筛选样式 */
        .ai-product-item {
          background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
          border: 1px solid #e2e8f0;
          border-radius: 8px;
          padding: 12px;
          margin-bottom: 12px;
        }

        .ai-product-item .color-filter-header {
          margin-bottom: 8px;
        }

        .product-label.from-analysis {
          background: #f0f9ff;
          color: #0369a1;
          padding: 2px 8px;
          border-radius: 12px;
          font-weight: 600;
          font-size: 13px;
          border: 1px solid #bae6fd;
        }

        .product-description-mini {
          font-size: 12px;
          color: #64748b;
          margin: 8px 0;
          padding: 6px 8px;
          background: #f8fafc;
          border-radius: 4px;
          border-left: 3px solid #8b5cf6;
          line-height: 1.4;
        }

        .color-picker-header {
          margin-bottom: 12px;
          padding-bottom: 8px;
          border-bottom: 1px solid #e2e8f0;
        }

        .color-picker-header h5 {
          margin: 0 0 4px 0;
          font-size: 14px;
          font-weight: 600;
          color: #334155;
        }

        .color-hint {
          margin: 0;
          font-size: 12px;
          color: #64748b;
          font-style: italic;
        }

        .color-actions {
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid #e2e8f0;
        }

        .reset-color-button {
          background: linear-gradient(135deg, #f59e0b, #d97706);
          color: white;
          border: none;
          border-radius: 6px;
          padding: 6px 12px;
          font-size: 12px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .reset-color-button:hover {
          background: linear-gradient(135deg, #d97706, #b45309);
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(217, 119, 6, 0.3);
        }

        .no-analysis-hint {
          text-align: center;
          padding: 24px;
          background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
          border: 2px dashed #cbd5e1;
          border-radius: 8px;
          color: #64748b;
        }

        .no-analysis-hint p {
          margin: 0;
          font-size: 14px;
          font-style: italic;
        }

        .ai-product-item .color-edit-button {
          background: #3b82f6;
          color: white;
          border: none;
          border-radius: 4px;
          font-weight: 500;
          font-size: 11px;
          padding: 4px 8px;
        }

        .ai-product-item .color-edit-button:hover {
          background: #2563eb;
          transform: translateY(-1px);
        }

        /* AI风格类别样式 */
        .ai-style-category {
          background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
          border: 1px solid #e2e8f0;
          border-radius: 8px;
          padding: 12px;
          margin-bottom: 12px;
        }

        .style-category-header {
          margin-bottom: 8px;
        }

        .ai-style-category .style-category-title {
          margin-bottom: 4px;
        }

        .ai-style-category .product-description-mini {
          margin: 4px 0 8px 0;
        }

        .ai-style-category .filter-tags {
          margin-top: 8px;
        }

        .ai-style-category .filter-tag.from-analysis {
          background: #f0f9ff;
          border: 1px solid #bae6fd;
          color: #0369a1;
        }

        .ai-style-category .filter-tag.from-analysis:hover {
          background: #e0f2fe;
          border-color: #7dd3fc;
          color: #0284c7;
          transform: translateY(-1px);
        }

        .ai-style-category .filter-tag.from-analysis.active {
          background: #3b82f6;
          border-color: #3b82f6;
          color: white;
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
        }

        .ai-style-category .filter-tag.from-analysis.active .analysis-star {
          opacity: 1;
        }

        /* 合并的商品筛选样式 */
        .product-filters {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .product-filter-item {
          background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
          border: 1px solid #e2e8f0;
          border-radius: 12px;
          padding: 16px;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .product-header {
          margin-bottom: 12px;
          padding-bottom: 8px;
          border-bottom: 1px solid #e2e8f0;
        }

        .product-title {
          margin: 0 0 6px 0;
          font-size: 15px;
          font-weight: 600;
        }

        .product-color-section {
          margin-bottom: 12px;
        }

        .product-style-section {
          margin-top: 12px;
          padding-top: 12px;
          border-top: 1px solid #e2e8f0;
        }

        .filter-section-label {
          font-size: 13px;
          font-weight: 600;
          color: #374151;
          margin: 0 0 8px 0;
          display: block;
        }

        .product-color-section .color-filter-label {
          font-size: 13px;
        }

        .color-picker-header h6 {
          margin: 0 0 4px 0;
          font-size: 13px;
          font-weight: 600;
          color: #334155;
        }

        .style-tag {
          background: #f0f9ff !important;
          border: 1px solid #bae6fd !important;
          color: #0369a1 !important;
        }

        .style-tag:hover {
          background: #e0f2fe !important;
          border-color: #7dd3fc !important;
          color: #0284c7 !important;
          transform: translateY(-1px);
        }

        .style-tag.active {
          background: #3b82f6 !important;
          border-color: #3b82f6 !important;
          color: white !important;
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
        }

        .traditional-filters {
          display: flex;
          flex-direction: column;
          gap: 16px;
        }

        .traditional-color-section,
        .traditional-style-section {
          background: white;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          padding: 12px;
        }

        .traditional-color-section .filter-section-label,
        .traditional-style-section .filter-section-label {
          margin-bottom: 12px;
          color: #6b7280;
        }

        @media (max-width: 768px) {
          .product-filter-item {
            padding: 12px;
          }

          .product-header {
            margin-bottom: 8px;
          }

          .product-color-section,
          .product-style-section {
            margin-bottom: 8px;
          }
        }

        /* 自定义标签筛选样式 */
        .custom-tag-selector-wrapper {
          margin-bottom: 8px;
        }

        .selected-tags-info {
          font-size: 12px;
          color: #6b7280;
          font-style: italic;
          margin-top: 4px;
        }

        .section-title {
          display: flex;
          align-items: center;
        }
      `}</style>
    </div>
  );
};

export default FilterPanel;
