import React, { useState } from 'react';
import { 
  Palette, 
  Sparkles, 
  TrendingUp, 
  MapPin, 
  Lightbulb,
  BarChart3,
  ChevronDown,
  ChevronUp,
  Target
} from 'lucide-react';

// 丰富的分析结果类型定义
interface EnrichedAnalysisResult {
  original_result: any;
  analysis_time_ms: number;
  analyzed_at: string;
  color_analysis: ColorAnalysisDetails;
  style_analysis: StyleAnalysisDetails;
  product_analysis: ProductAnalysisDetails;
  environment_analysis: EnvironmentAnalysisDetails;
  styling_suggestions: StylingSuggestions;
  statistics: AnalysisStatistics;
}

interface ColorAnalysisDetails {
  overall_color_description: string;
  dress_color_hex: string;
  environment_color_hex: string;
  color_harmony: ColorHarmonyAnalysis;
  color_temperature: ColorTemperatureAnalysis;
  color_contrast: number;
}

interface ColorHarmonyAnalysis {
  harmony_score: number;
  harmony_type: string;
  harmony_description: string;
}

interface ColorTemperatureAnalysis {
  overall_temperature: string;
  dress_temperature: string;
  environment_temperature: string;
  temperature_match: number;
}

interface StyleAnalysisDetails {
  primary_styles: string[];
  secondary_styles: string[];
  style_consistency: number;
  style_complexity: string;
  suitable_occasions: string[];
  seasonal_suitability: string[];
}

interface ProductAnalysisDetails {
  product_count_by_category: Record<string, number>;
  best_matched_product: string | null;
  color_match_statistics: ColorMatchStatistics;
  style_diversity: number;
  outfit_completeness: number;
}

interface ColorMatchStatistics {
  avg_dress_match: number;
  avg_environment_match: number;
  max_match: number;
  min_match: number;
}

interface EnvironmentAnalysisDetails {
  environment_type: string;
  lighting_condition: string;
  background_complexity: string;
  environment_suitability: number;
  photo_quality_assessment: PhotoQualityAssessment;
}

interface PhotoQualityAssessment {
  overall_quality: number;
  clarity: string;
  composition: string;
  lighting_quality: string;
}

interface StylingSuggestions {
  improvement_suggestions: string[];
  alternative_suggestions: string[];
  accessory_suggestions: string[];
  occasion_suggestions: string[];
}

interface AnalysisStatistics {
  total_products: number;
  total_styles: number;
  total_environment_tags: number;
  avg_description_length: number;
  analysis_complexity: number;
}

interface EnrichedAnalysisDisplayProps {
  enrichedResult: EnrichedAnalysisResult;
}

/**
 * 丰富的图像分析结果展示组件
 * 提供详细的分析信息和可视化展示
 */
export const EnrichedAnalysisDisplay: React.FC<EnrichedAnalysisDisplayProps> = ({
  enrichedResult
}) => {
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['overview']));

  const toggleSection = (section: string) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(section)) {
      newExpanded.delete(section);
    } else {
      newExpanded.add(section);
    }
    setExpandedSections(newExpanded);
  };

  const formatPercentage = (value: number) => `${(value * 100).toFixed(1)}%`;
  const formatTime = (ms: number) => `${ms}ms`;

  return (
    <div className="space-y-6 p-6 bg-white rounded-lg shadow-lg">
      {/* 标题和基本信息 */}
      <div className="border-b pb-4">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">
          🎨 智能服装分析报告
        </h2>
        <div className="flex items-center gap-4 text-sm text-gray-600">
          <span>分析时间: {formatTime(enrichedResult.analysis_time_ms)}</span>
          <span>分析于: {new Date(enrichedResult.analyzed_at).toLocaleString()}</span>
          <span>复杂度: {formatPercentage(enrichedResult.statistics.analysis_complexity)}</span>
        </div>
      </div>

      {/* 概览统计 */}
      <ExpandableSection
        title="📊 分析概览"
        icon={<BarChart3 className="w-5 h-5" />}
        isExpanded={expandedSections.has('overview')}
        onToggle={() => toggleSection('overview')}
      >
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard
            label="识别产品"
            value={enrichedResult.statistics.total_products}
            suffix="件"
            color="blue"
          />
          <StatCard
            label="风格标签"
            value={enrichedResult.statistics.total_styles}
            suffix="个"
            color="green"
          />
          <StatCard
            label="环境标签"
            value={enrichedResult.statistics.total_environment_tags}
            suffix="个"
            color="purple"
          />
          <StatCard
            label="搭配完整度"
            value={formatPercentage(enrichedResult.product_analysis.outfit_completeness)}
            color="orange"
          />
        </div>
      </ExpandableSection>

      {/* 颜色分析 */}
      <ExpandableSection
        title="🎨 色彩分析"
        icon={<Palette className="w-5 h-5" />}
        isExpanded={expandedSections.has('color')}
        onToggle={() => toggleSection('color')}
      >
        <div className="space-y-4">
          <p className="text-gray-700">{enrichedResult.color_analysis.overall_color_description}</p>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 主色调展示 */}
            <div className="space-y-3">
              <h4 className="font-semibold text-gray-900">主色调</h4>
              <div className="flex items-center gap-3">
                <div 
                  className="w-12 h-12 rounded-lg border-2 border-gray-200"
                  style={{ backgroundColor: enrichedResult.color_analysis.dress_color_hex }}
                />
                <div>
                  <p className="font-medium">{enrichedResult.color_analysis.dress_color_hex}</p>
                  <p className="text-sm text-gray-600">{enrichedResult.color_analysis.color_temperature.dress_temperature}</p>
                </div>
              </div>
            </div>

            {/* 环境色调 */}
            <div className="space-y-3">
              <h4 className="font-semibold text-gray-900">环境色调</h4>
              <div className="flex items-center gap-3">
                <div 
                  className="w-12 h-12 rounded-lg border-2 border-gray-200"
                  style={{ backgroundColor: enrichedResult.color_analysis.environment_color_hex }}
                />
                <div>
                  <p className="font-medium">{enrichedResult.color_analysis.environment_color_hex}</p>
                  <p className="text-sm text-gray-600">{enrichedResult.color_analysis.color_temperature.environment_temperature}</p>
                </div>
              </div>
            </div>
          </div>

          {/* 色彩和谐度 */}
          <div className="bg-gray-50 p-4 rounded-lg">
            <div className="flex items-center justify-between mb-2">
              <span className="font-medium">色彩和谐度</span>
              <span className="text-lg font-bold text-blue-600">
                {formatPercentage(enrichedResult.color_analysis.color_harmony.harmony_score)}
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2 mb-2">
              <div 
                className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                style={{ width: `${enrichedResult.color_analysis.color_harmony.harmony_score * 100}%` }}
              />
            </div>
            <p className="text-sm text-gray-600">{enrichedResult.color_analysis.color_harmony.harmony_description}</p>
          </div>
        </div>
      </ExpandableSection>

      {/* 风格分析 */}
      <ExpandableSection
        title="✨ 风格分析"
        icon={<Sparkles className="w-5 h-5" />}
        isExpanded={expandedSections.has('style')}
        onToggle={() => toggleSection('style')}
      >
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h4 className="font-semibold text-gray-900 mb-3">主要风格</h4>
              <div className="flex flex-wrap gap-2">
                {enrichedResult.style_analysis.primary_styles.map((style, index) => (
                  <span key={index} className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
                    {style}
                  </span>
                ))}
              </div>
            </div>

            <div>
              <h4 className="font-semibold text-gray-900 mb-3">次要风格</h4>
              <div className="flex flex-wrap gap-2">
                {enrichedResult.style_analysis.secondary_styles.map((style, index) => (
                  <span key={index} className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm">
                    {style}
                  </span>
                ))}
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-gray-50 p-4 rounded-lg text-center">
              <p className="text-sm text-gray-600 mb-1">风格一致性</p>
              <p className="text-2xl font-bold text-green-600">
                {formatPercentage(enrichedResult.style_analysis.style_consistency)}
              </p>
            </div>
            <div className="bg-gray-50 p-4 rounded-lg text-center">
              <p className="text-sm text-gray-600 mb-1">风格复杂度</p>
              <p className="text-lg font-semibold text-purple-600">
                {enrichedResult.style_analysis.style_complexity}
              </p>
            </div>
            <div className="bg-gray-50 p-4 rounded-lg text-center">
              <p className="text-sm text-gray-600 mb-1">风格多样性</p>
              <p className="text-2xl font-bold text-orange-600">
                {formatPercentage(enrichedResult.product_analysis.style_diversity)}
              </p>
            </div>
          </div>
        </div>
      </ExpandableSection>

      {/* 产品分析 */}
      <ExpandableSection
        title="👕 产品分析"
        icon={<Target className="w-5 h-5" />}
        isExpanded={expandedSections.has('products')}
        onToggle={() => toggleSection('products')}
      >
        <div className="space-y-4">
          {/* 产品类别统计 */}
          <div>
            <h4 className="font-semibold text-gray-900 mb-3">产品类别分布</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {Object.entries(enrichedResult.product_analysis.product_count_by_category).map(([category, count]) => (
                <div key={category} className="bg-gray-50 p-3 rounded-lg text-center">
                  <p className="text-sm text-gray-600">{category}</p>
                  <p className="text-xl font-bold text-blue-600">{count}</p>
                </div>
              ))}
            </div>
          </div>

          {/* 最佳匹配产品 */}
          {enrichedResult.product_analysis.best_matched_product && (
            <div className="bg-green-50 p-4 rounded-lg">
              <h4 className="font-semibold text-green-900 mb-2">🏆 最佳匹配产品</h4>
              <p className="text-green-800">{enrichedResult.product_analysis.best_matched_product}</p>
            </div>
          )}

          {/* 颜色匹配统计 */}
          <div>
            <h4 className="font-semibold text-gray-900 mb-3">颜色匹配度统计</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-1">平均服装匹配</p>
                <p className="text-lg font-bold text-blue-600">
                  {formatPercentage(enrichedResult.product_analysis.color_match_statistics.avg_dress_match)}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-1">平均环境匹配</p>
                <p className="text-lg font-bold text-green-600">
                  {formatPercentage(enrichedResult.product_analysis.color_match_statistics.avg_environment_match)}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-1">最高匹配度</p>
                <p className="text-lg font-bold text-purple-600">
                  {formatPercentage(enrichedResult.product_analysis.color_match_statistics.max_match)}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-gray-600 mb-1">最低匹配度</p>
                <p className="text-lg font-bold text-orange-600">
                  {formatPercentage(enrichedResult.product_analysis.color_match_statistics.min_match)}
                </p>
              </div>
            </div>
          </div>
        </div>
      </ExpandableSection>

      {/* 环境分析 */}
      <ExpandableSection
        title="📍 环境分析"
        icon={<MapPin className="w-5 h-5" />}
        isExpanded={expandedSections.has('environment')}
        onToggle={() => toggleSection('environment')}
      >
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-gray-50 p-4 rounded-lg">
              <h4 className="font-semibold text-gray-900 mb-2">环境类型</h4>
              <p className="text-blue-600 font-medium">{enrichedResult.environment_analysis.environment_type}</p>
            </div>
            <div className="bg-gray-50 p-4 rounded-lg">
              <h4 className="font-semibold text-gray-900 mb-2">光照条件</h4>
              <p className="text-green-600 font-medium">{enrichedResult.environment_analysis.lighting_condition}</p>
            </div>
            <div className="bg-gray-50 p-4 rounded-lg">
              <h4 className="font-semibold text-gray-900 mb-2">背景复杂度</h4>
              <p className="text-purple-600 font-medium">{enrichedResult.environment_analysis.background_complexity}</p>
            </div>
          </div>

          {/* 拍摄质量评估 */}
          <div className="bg-blue-50 p-4 rounded-lg">
            <h4 className="font-semibold text-blue-900 mb-3">📸 拍摄质量评估</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <p className="text-sm text-blue-700 mb-1">整体质量</p>
                <p className="text-xl font-bold text-blue-800">
                  {formatPercentage(enrichedResult.environment_analysis.photo_quality_assessment.overall_quality)}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-blue-700 mb-1">清晰度</p>
                <p className="text-lg font-semibold text-blue-800">
                  {enrichedResult.environment_analysis.photo_quality_assessment.clarity}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-blue-700 mb-1">构图质量</p>
                <p className="text-lg font-semibold text-blue-800">
                  {enrichedResult.environment_analysis.photo_quality_assessment.composition}
                </p>
              </div>
              <div className="text-center">
                <p className="text-sm text-blue-700 mb-1">光线质量</p>
                <p className="text-lg font-semibold text-blue-800">
                  {enrichedResult.environment_analysis.photo_quality_assessment.lighting_quality}
                </p>
              </div>
            </div>
          </div>
        </div>
      </ExpandableSection>

      {/* 搭配建议 */}
      <ExpandableSection
        title="💡 搭配建议"
        icon={<Lightbulb className="w-5 h-5" />}
        isExpanded={expandedSections.has('suggestions')}
        onToggle={() => toggleSection('suggestions')}
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <SuggestionCard
            title="改进建议"
            suggestions={enrichedResult.styling_suggestions.improvement_suggestions}
            color="blue"
          />
          <SuggestionCard
            title="替代搭配"
            suggestions={enrichedResult.styling_suggestions.alternative_suggestions}
            color="green"
          />
          <SuggestionCard
            title="配饰建议"
            suggestions={enrichedResult.styling_suggestions.accessory_suggestions}
            color="purple"
          />
          <SuggestionCard
            title="场合建议"
            suggestions={enrichedResult.styling_suggestions.occasion_suggestions}
            color="orange"
          />
        </div>
      </ExpandableSection>

      {/* 适合场合和季节 */}
      <ExpandableSection
        title="🎯 适配分析"
        icon={<TrendingUp className="w-5 h-5" />}
        isExpanded={expandedSections.has('suitability')}
        onToggle={() => toggleSection('suitability')}
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <h4 className="font-semibold text-gray-900 mb-3">适合场合</h4>
            <div className="flex flex-wrap gap-2">
              {enrichedResult.style_analysis.suitable_occasions.map((occasion, index) => (
                <span key={index} className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
                  {occasion}
                </span>
              ))}
            </div>
          </div>
          <div>
            <h4 className="font-semibold text-gray-900 mb-3">季节适配</h4>
            <div className="flex flex-wrap gap-2">
              {enrichedResult.style_analysis.seasonal_suitability.map((season, index) => (
                <span key={index} className="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm">
                  {season}
                </span>
              ))}
            </div>
          </div>
        </div>
      </ExpandableSection>
    </div>
  );
};

// 可展开区域组件
interface ExpandableSectionProps {
  title: string;
  icon: React.ReactNode;
  isExpanded: boolean;
  onToggle: () => void;
  children: React.ReactNode;
}

const ExpandableSection: React.FC<ExpandableSectionProps> = ({
  title,
  icon,
  isExpanded,
  onToggle,
  children
}) => (
  <div className="border border-gray-200 rounded-lg overflow-hidden">
    <button
      onClick={onToggle}
      className="w-full px-4 py-3 bg-gray-50 hover:bg-gray-100 flex items-center justify-between transition-colors"
    >
      <div className="flex items-center gap-2">
        {icon}
        <span className="font-semibold text-gray-900">{title}</span>
      </div>
      {isExpanded ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
    </button>
    {isExpanded && (
      <div className="p-4 border-t border-gray-200">
        {children}
      </div>
    )}
  </div>
);

// 统计卡片组件
interface StatCardProps {
  label: string;
  value: string | number;
  suffix?: string;
  color: 'blue' | 'green' | 'purple' | 'orange';
}

const StatCard: React.FC<StatCardProps> = ({ label, value, suffix = '', color }) => {
  const colorClasses = {
    blue: 'text-blue-600 bg-blue-50',
    green: 'text-green-600 bg-green-50',
    purple: 'text-purple-600 bg-purple-50',
    orange: 'text-orange-600 bg-orange-50',
  };

  return (
    <div className={`p-4 rounded-lg ${colorClasses[color]}`}>
      <p className="text-sm font-medium text-gray-600 mb-1">{label}</p>
      <p className="text-2xl font-bold">
        {value}{suffix}
      </p>
    </div>
  );
};

// 建议卡片组件
interface SuggestionCardProps {
  title: string;
  suggestions: string[];
  color: 'blue' | 'green' | 'purple' | 'orange';
}

const SuggestionCard: React.FC<SuggestionCardProps> = ({ title, suggestions, color }) => {
  const colorClasses = {
    blue: 'bg-blue-50 border-blue-200',
    green: 'bg-green-50 border-green-200',
    purple: 'bg-purple-50 border-purple-200',
    orange: 'bg-orange-50 border-orange-200',
  };

  const textColorClasses = {
    blue: 'text-blue-900',
    green: 'text-green-900',
    purple: 'text-purple-900',
    orange: 'text-orange-900',
  };

  return (
    <div className={`p-4 rounded-lg border ${colorClasses[color]}`}>
      <h4 className={`font-semibold mb-3 ${textColorClasses[color]}`}>{title}</h4>
      <ul className="space-y-2">
        {suggestions.map((suggestion, index) => (
          <li key={index} className="flex items-start gap-2">
            <span className="text-gray-400 mt-1">•</span>
            <span className="text-gray-700 text-sm">{suggestion}</span>
          </li>
        ))}
      </ul>
    </div>
  );
};
