import React, { useState, useCallback } from 'react';
import { ColorHSV, ColorFilter, ColorThresholds, DEFAULT_COLOR_FILTER } from '../../types/outfitSearch';
import { ColorPicker } from './ColorPicker';
import { Palette, Eye, EyeOff, Settings, RotateCcw } from 'lucide-react';
import * as ColorUtils from '../../utils/colorUtils';

/**
 * 颜色检测过滤器组件
 * 遵循 promptx/frontend-developer 标准的UI/UX优化
 */

interface ColorDetectionFilterProps {
  selectedCategories: string[];
  colorFilters: Record<string, ColorFilter>;
  colorThresholds: ColorThresholds;
  onColorFilterChange: (category: string, colorFilter: ColorFilter) => void;
  className?: string;
}

export const ColorDetectionFilter: React.FC<ColorDetectionFilterProps> = ({
  selectedCategories,
  colorFilters,
  colorThresholds,
  onColorFilterChange,
  className = '',
}) => {
  const [activeCategory, setActiveCategory] = useState<string>(selectedCategories[0] || '');
  const [showAdvancedSettings, setShowAdvancedSettings] = useState<Record<string, boolean>>({});

  // 获取类别的颜色过滤器
  const getCategoryColorFilter = useCallback((category: string): ColorFilter => {
    return colorFilters[category] || {
      ...DEFAULT_COLOR_FILTER,
      hue_threshold: colorThresholds.default_hue_threshold,
      saturation_threshold: colorThresholds.default_saturation_threshold,
      value_threshold: colorThresholds.default_value_threshold,
    };
  }, [colorFilters, colorThresholds]);

  // 处理颜色过滤器启用/禁用
  const handleToggleColorFilter = useCallback((category: string) => {
    const currentFilter = getCategoryColorFilter(category);
    onColorFilterChange(category, {
      ...currentFilter,
      enabled: !currentFilter.enabled,
    });
  }, [getCategoryColorFilter, onColorFilterChange]);

  // 处理颜色变化
  const handleColorChange = useCallback((category: string, color: ColorHSV) => {
    const currentFilter = getCategoryColorFilter(category);
    onColorFilterChange(category, {
      ...currentFilter,
      color,
      enabled: true, // 选择颜色时自动启用
    });
  }, [getCategoryColorFilter, onColorFilterChange]);

  // 处理阈值变化
  const handleThresholdChange = useCallback((
    category: string, 
    thresholdType: 'hue_threshold' | 'saturation_threshold' | 'value_threshold',
    value: number
  ) => {
    const currentFilter = getCategoryColorFilter(category);
    onColorFilterChange(category, {
      ...currentFilter,
      [thresholdType]: value,
    });
  }, [getCategoryColorFilter, onColorFilterChange]);

  // 重置颜色过滤器
  const handleResetColorFilter = useCallback((category: string) => {
    onColorFilterChange(category, {
      ...DEFAULT_COLOR_FILTER,
      hue_threshold: colorThresholds.default_hue_threshold,
      saturation_threshold: colorThresholds.default_saturation_threshold,
      value_threshold: colorThresholds.default_value_threshold,
    });
  }, [onColorFilterChange, colorThresholds]);

  // 切换高级设置显示
  const toggleAdvancedSettings = useCallback((category: string) => {
    setShowAdvancedSettings(prev => ({
      ...prev,
      [category]: !prev[category],
    }));
  }, []);

  // 预设颜色
  const presetColors: { name: string; color: ColorHSV }[] = [
    { name: '红色', color: { hue: 0, saturation: 1, value: 1 } },
    { name: '橙色', color: { hue: 0.083, saturation: 1, value: 1 } },
    { name: '黄色', color: { hue: 0.167, saturation: 1, value: 1 } },
    { name: '绿色', color: { hue: 0.333, saturation: 1, value: 1 } },
    { name: '蓝色', color: { hue: 0.667, saturation: 1, value: 1 } },
    { name: '紫色', color: { hue: 0.833, saturation: 1, value: 1 } },
    { name: '黑色', color: { hue: 0, saturation: 0, value: 0 } },
    { name: '白色', color: { hue: 0, saturation: 0, value: 1 } },
  ];

  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) => {
              const filter = getCategoryColorFilter(category);
              return (
                <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}
                  {filter.enabled && (
                    <span className="ml-1 w-2 h-2 rounded-full bg-green-400 inline-block"></span>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* 当前类别的颜色过滤器 */}
      {activeCategory && (
        <div className="space-y-4">
          {(() => {
            const filter = getCategoryColorFilter(activeCategory);
            
            return (
              <>
                {/* 启用/禁用开关 */}
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${
                      filter.enabled ? 'bg-green-100' : 'bg-gray-100'
                    }`}>
                      {filter.enabled ? (
                        <Eye className="w-4 h-4 text-green-600" />
                      ) : (
                        <EyeOff className="w-4 h-4 text-gray-400" />
                      )}
                    </div>
                    <div>
                      <h4 className="text-sm font-medium text-gray-700">
                        {activeCategory} 颜色检测
                      </h4>
                      <p className="text-xs text-gray-500">
                        {filter.enabled ? '已启用颜色过滤' : '点击启用颜色过滤'}
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    {filter.enabled && (
                      <button
                        onClick={() => handleResetColorFilter(activeCategory)}
                        className="btn-icon btn-ghost btn-sm"
                        title="重置设置"
                      >
                        <RotateCcw className="w-4 h-4" />
                      </button>
                    )}
                    
                    <button
                      onClick={() => handleToggleColorFilter(activeCategory)}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                        filter.enabled ? 'bg-green-500' : 'bg-gray-300'
                      }`}
                    >
                      <span
                        className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                          filter.enabled ? 'translate-x-6' : 'translate-x-1'
                        }`}
                      />
                    </button>
                  </div>
                </div>

                {/* 颜色选择器 */}
                {filter.enabled && (
                  <div className="space-y-4">
                    {/* 预设颜色 */}
                    <div className="space-y-2">
                      <h5 className="text-sm font-medium text-gray-700">快速选择</h5>
                      <div className="grid grid-cols-4 gap-2">
                        {presetColors.map((preset) => (
                          <button
                            key={preset.name}
                            onClick={() => handleColorChange(activeCategory, preset.color)}
                            className="flex flex-col items-center gap-1 p-2 rounded-lg hover:bg-gray-50 transition-colors duration-150"
                            title={preset.name}
                          >
                            <div
                              className="w-8 h-8 rounded-full border-2 border-gray-200"
                              style={{ backgroundColor: ColorUtils.hsvToHex(preset.color) }}
                            />
                            <span className="text-xs text-gray-600">{preset.name}</span>
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* 自定义颜色选择器 */}
                    <div className="space-y-2">
                      <h5 className="text-sm font-medium text-gray-700">自定义颜色</h5>
                      <ColorPicker
                        color={filter.color}
                        onChange={(color) => handleColorChange(activeCategory, color)}
                      />
                    </div>

                    {/* 高级设置 */}
                    <div className="space-y-2">
                      <button
                        onClick={() => toggleAdvancedSettings(activeCategory)}
                        className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-800"
                      >
                        <Settings className="w-4 h-4" />
                        <span>高级设置</span>
                        <span className={`transform transition-transform ${
                          showAdvancedSettings[activeCategory] ? 'rotate-180' : ''
                        }`}>
                          ▼
                        </span>
                      </button>

                      {showAdvancedSettings[activeCategory] && (
                        <div className="space-y-3 p-3 bg-gray-50 rounded-lg">
                          {/* 色相阈值 */}
                          <div className="space-y-1">
                            <label className="text-xs font-medium text-gray-700">
                              色相阈值: {(filter.hue_threshold * 100).toFixed(1)}%
                            </label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={filter.hue_threshold}
                              onChange={(e) => handleThresholdChange(
                                activeCategory, 
                                'hue_threshold', 
                                parseFloat(e.target.value)
                              )}
                              className="w-full"
                            />
                          </div>

                          {/* 饱和度阈值 */}
                          <div className="space-y-1">
                            <label className="text-xs font-medium text-gray-700">
                              饱和度阈值: {(filter.saturation_threshold * 100).toFixed(1)}%
                            </label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={filter.saturation_threshold}
                              onChange={(e) => handleThresholdChange(
                                activeCategory, 
                                'saturation_threshold', 
                                parseFloat(e.target.value)
                              )}
                              className="w-full"
                            />
                          </div>

                          {/* 明度阈值 */}
                          <div className="space-y-1">
                            <label className="text-xs font-medium text-gray-700">
                              明度阈值: {(filter.value_threshold * 100).toFixed(1)}%
                            </label>
                            <input
                              type="range"
                              min="0"
                              max="0.5"
                              step="0.01"
                              value={filter.value_threshold}
                              onChange={(e) => handleThresholdChange(
                                activeCategory, 
                                'value_threshold', 
                                parseFloat(e.target.value)
                              )}
                              className="w-full"
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </>
            );
          })()}
        </div>
      )}

      {/* 使用提示 */}
      <div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
        <p>🎨 提示：颜色检测帮助匹配特定颜色范围的服装单品</p>
      </div>
    </div>
  );
};
