import React, { useState, useCallback } from 'react';
import {
  SearchConfig,
  ColorFilter,
  COMMON_CATEGORIES,
  COMMON_ENVIRONMENTS,
  COMMON_DESIGN_STYLES
} from '../../types/outfitSearch';
import { CategoryFilterSelector } from './CategoryFilterSelector';
import { EnvironmentTagSelector } from './EnvironmentTagSelector';
import { DesignStyleSelector } from './DesignStyleSelector';
import { ColorDetectionFilter } from './ColorDetectionFilter';
import { Filter, ChevronDown, Settings, Palette, Tag, Grid } from 'lucide-react';

/**
 * 高级过滤器面板组件
 * 遵循 Tauri 开发规范和 promptx/frontend-developer 标准
 */

interface AdvancedFilterPanelProps {
  config: SearchConfig;
  onConfigChange: (config: SearchConfig) => void;
  isVisible: boolean;
  onToggle: () => void;
  className?: string;
}

export const AdvancedFilterPanel: React.FC<AdvancedFilterPanelProps> = ({
  config,
  onConfigChange,
  isVisible,
  onToggle,
  className = '',
}) => {
  const [activeTab, setActiveTab] = useState<'categories' | 'environments' | 'styles' | 'colors'>('categories');

  // 处理类别变化
  const handleCategoriesChange = useCallback((categories: string[]) => {
    onConfigChange({
      ...config,
      categories,
    });
  }, [config, onConfigChange]);

  // 处理环境标签变化
  const handleEnvironmentsChange = useCallback((environments: string[]) => {
    onConfigChange({
      ...config,
      environments,
    });
  }, [config, onConfigChange]);

  // 处理设计风格变化
  const handleDesignStylesChange = useCallback((category: string, styles: string[]) => {
    const newDesignStyles = { ...config.design_styles };
    if (styles.length === 0) {
      delete newDesignStyles[category];
    } else {
      newDesignStyles[category] = styles;
    }
    
    onConfigChange({
      ...config,
      design_styles: newDesignStyles,
    });
  }, [config, onConfigChange]);

  // 处理颜色过滤器变化
  const handleColorFilterChange = useCallback((category: string, colorFilter: ColorFilter) => {
    const newColorFilters = { ...config.color_filters };
    if (!colorFilter.enabled) {
      delete newColorFilters[category];
    } else {
      newColorFilters[category] = colorFilter;
    }
    
    onConfigChange({
      ...config,
      color_filters: newColorFilters,
    });
  }, [config, onConfigChange]);

  // 计算活跃过滤器数量
  const getActiveFiltersCount = useCallback(() => {
    let count = 0;
    count += config.categories.length;
    count += config.environments.length;
    count += Object.values(config.color_filters).filter(f => f.enabled).length;
    count += Object.values(config.design_styles).reduce((acc, styles) => acc + styles.length, 0);
    return count;
  }, [config]);

  const activeFiltersCount = getActiveFiltersCount();

  // 标签页配置
  const tabs = [
    { 
      id: 'categories' as const, 
      label: '类别', 
      icon: Grid, 
      count: config.categories.length 
    },
    { 
      id: 'environments' as const, 
      label: '环境', 
      icon: Tag, 
      count: config.environments.length 
    },
    { 
      id: 'styles' as const, 
      label: '风格', 
      icon: Settings, 
      count: Object.values(config.design_styles).reduce((acc, styles) => acc + styles.length, 0) 
    },
    { 
      id: 'colors' as const, 
      label: '颜色', 
      icon: Palette, 
      count: Object.values(config.color_filters).filter(f => f.enabled).length 
    },
  ];

  if (!isVisible) {
    return null;
  }

  return (
    <div className={`card animate-slide-in-up ${className}`}>
      {/* 面板头部 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200">
        <div className="flex items-center gap-3">
          <div className="icon-container primary w-8 h-8">
            <Filter className="w-4 h-4" />
          </div>
          <div>
            <h3 className="text-heading-4 text-high-emphasis">高级过滤器</h3>
            <p className="text-xs text-medium-emphasis">
              精确控制搜索条件 {activeFiltersCount > 0 && `(${activeFiltersCount} 个活跃)`}
            </p>
          </div>
        </div>
        
        <button
          onClick={onToggle}
          className="btn-icon btn-ghost hover-lift"
          aria-label="收起高级过滤器"
        >
          <ChevronDown className="w-5 h-5 rotate-180" />
        </button>
      </div>

      {/* 标签页导航 */}
      <div className="flex border-b border-gray-200">
        {tabs.map((tab) => {
          const Icon = tab.icon;
          const isActive = activeTab === tab.id;
          
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium transition-all duration-200 ${
                isActive
                  ? 'text-primary-600 border-b-2 border-primary-500 bg-primary-50'
                  : 'text-gray-600 hover:text-gray-800 hover:bg-gray-50'
              }`}
            >
              <Icon className="w-4 h-4" />
              <span>{tab.label}</span>
              {tab.count > 0 && (
                <span className={`text-xs px-2 py-0.5 rounded-full ${
                  isActive 
                    ? 'bg-primary-500 text-white' 
                    : 'bg-gray-200 text-gray-600'
                }`}>
                  {tab.count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* 标签页内容 */}
      <div className="p-4">
        {activeTab === 'categories' && (
          <CategoryFilterSelector
            selectedCategories={config.categories}
            availableCategories={COMMON_CATEGORIES}
            onCategoriesChange={handleCategoriesChange}
          />
        )}

        {activeTab === 'environments' && (
          <EnvironmentTagSelector
            selectedEnvironments={config.environments}
            availableEnvironments={COMMON_ENVIRONMENTS}
            onEnvironmentsChange={handleEnvironmentsChange}
          />
        )}

        {activeTab === 'styles' && (
          <DesignStyleSelector
            selectedCategories={config.categories}
            designStyles={config.design_styles}
            availableStyles={COMMON_DESIGN_STYLES}
            onDesignStylesChange={handleDesignStylesChange}
          />
        )}

        {activeTab === 'colors' && (
          <ColorDetectionFilter
            selectedCategories={config.categories}
            colorFilters={config.color_filters}
            colorThresholds={config.color_thresholds}
            onColorFilterChange={handleColorFilterChange}
          />
        )}
      </div>

      {/* 底部操作 */}
      <div className="flex items-center justify-between p-4 border-t border-gray-200 bg-gray-50">
        <div className="text-sm text-medium-emphasis">
          {activeFiltersCount === 0 ? '未设置过滤条件' : `已设置 ${activeFiltersCount} 个过滤条件`}
        </div>
        
        {activeFiltersCount > 0 && (
          <button
            onClick={() => onConfigChange({
              ...config,
              categories: [],
              environments: [],
              color_filters: {},
              design_styles: {},
            })}
            className="btn btn-ghost btn-sm hover-lift"
          >
            清除全部
          </button>
        )}
      </div>
    </div>
  );
};
