/**
 * 一键匹配结果对话框组件
 * 遵循前端开发规范的组件设计原则
 */

import React from 'react';
import {
  X,
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  Target,
  Users,
  Film,
  TrendingUp,
  TrendingDown,
} from 'lucide-react';
import {
  BatchMatchingResult,
  BatchMatchingItemResult,
  getBatchMatchingStatusDisplay,
  getBatchMatchingStatusColor,
  formatDuration,
  calculateSuccessRate,
} from '../types/batchMatching';
import { BatchMatchingSummaryCard } from './BatchMatchingSummaryCard';

interface BatchMatchingResultDialogProps {
  isOpen: boolean;
  onClose: () => void;
  result: BatchMatchingResult | null;
  loading?: boolean;
}

export const BatchMatchingResultDialog: React.FC<BatchMatchingResultDialogProps> = ({
  isOpen,
  onClose,
  result,
  loading = false,
}) => {
  if (!isOpen) return null;

  // 导出匹配报告
  const exportMatchingReport = (result: BatchMatchingResult) => {
    const report = generateDetailedReport(result);
    const blob = new Blob([report], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `一键匹配报告_${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  // 复制匹配摘要
  const copyMatchingSummary = async (result: BatchMatchingResult) => {
    const summary = generateSummaryText(result);
    try {
      await navigator.clipboard.writeText(summary);
      alert('摘要已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      alert('复制失败，请手动复制');
    }
  };

  // 生成详细报告
  const generateDetailedReport = (result: BatchMatchingResult): string => {
    const lines = [
      '循环匹配详细报告',
      '='.repeat(50),
      '',
      `项目ID: ${result.project_id}`,
      `执行时间: ${new Date().toLocaleString()}`,
      `总耗时: ${formatDuration(result.total_duration_ms)}`,
      '',
      '循环匹配统计:',
      `---------------`,
      `总循环轮数: ${result.total_rounds}`,
      `成功轮数: ${result.successful_rounds}`,
      `终止原因: ${result.termination_reason}`,
      `素材是否耗尽: ${result.materials_exhausted ? '是' : '否'}`,
      '',
      '模板匹配统计:',
      `-------------`,
      `总模板绑定数: ${result.total_bindings}`,
      `成功匹配数: ${result.successful_matches}`,
      `失败匹配数: ${result.failed_matches}`,
      `跳过匹配数: ${result.skipped_bindings}`,
      `成功率: ${calculateSuccessRate(result.successful_matches, result.total_bindings)}%`,
      '',
      '汇总信息:',
      `---------`,
      `匹配片段总数: ${result.summary.total_segments_matched}`,
      `使用素材总数: ${result.summary.total_materials_used}`,
      `使用模特总数: ${result.summary.total_models_used}`,
      `平均成功率: ${(result.summary.average_success_rate * 100).toFixed(1)}%`,
    ];

    if (result.summary.best_matching_template) {
      lines.push(`最佳匹配模板: ${result.summary.best_matching_template}`);
    }
    if (result.summary.worst_matching_template) {
      lines.push(`最差匹配模板: ${result.summary.worst_matching_template}`);
    }

    lines.push('', '详细结果:', '---------');

    result.matching_results.forEach((item, index) => {
      lines.push(`${index + 1}. ${item.template_name}`);
      lines.push(`   状态: ${getBatchMatchingStatusDisplay(item.status)}`);
      lines.push(`   匹配轮次: 第${item.round_number}轮`);
      lines.push(`   尝试次数: ${item.attempts_count}`);
      lines.push(`   耗时: ${formatDuration(item.duration_ms)}`);
      if (item.binding_name) {
        lines.push(`   绑定名称: ${item.binding_name}`);
      }
      if (item.error_message) {
        lines.push(`   错误信息: ${item.error_message}`);
      }
      if (item.failure_reason) {
        lines.push(`   失败原因: ${item.failure_reason}`);
      }
      if (item.matching_result) {
        lines.push(`   成功率: ${Math.min((item.matching_result.statistics?.success_rate * 100 || 0), 100).toFixed(1)}%`);
      }
      lines.push('');
    });

    return lines.join('\n');
  };

  // 生成摘要文本
  const generateSummaryText = (result: BatchMatchingResult): string => {
    const successRate = calculateSuccessRate(result.successful_matches, result.total_bindings);
    return `循环匹配完成！完成 ${result.total_rounds} 轮匹配（成功 ${result.successful_rounds} 轮），总计 ${result.total_bindings} 个模板绑定，成功 ${result.successful_matches} 个，失败 ${result.failed_matches} 个，成功率 ${successRate}%。耗时 ${formatDuration(result.total_duration_ms)}，匹配片段 ${result.summary.total_segments_matched} 个，使用素材 ${result.summary.total_materials_used} 个。终止原因：${result.termination_reason}`;
  };

  const getOverallStatusIcon = () => {
    if (!result) return null;
    
    if (result.failed_matches === 0 && result.successful_matches > 0) {
      return <CheckCircle className="w-8 h-8 text-green-500" />;
    } else if (result.successful_matches > 0 && result.failed_matches > 0) {
      return <AlertCircle className="w-8 h-8 text-yellow-500" />;
    } else {
      return <XCircle className="w-8 h-8 text-red-500" />;
    }
  };

  const getOverallStatusText = () => {
    if (!result) return '';

    if (result.failed_matches === 0 && result.successful_matches > 0) {
      return '循环匹配成功完成';
    } else if (result.successful_matches > 0 && result.failed_matches > 0) {
      return '循环匹配部分成功';
    } else {
      return '循环匹配失败';
    }
  };

  const successRate = result ? calculateSuccessRate(result.successful_matches, result.total_bindings) : 0;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            {getOverallStatusIcon()}
            <div>
              <h2 className="text-xl font-semibold text-gray-900">
                {loading ? '正在执行循环匹配...' : getOverallStatusText()}
              </h2>
              {result && (
                <div className="text-sm text-gray-600">
                  <p>总计 {result.total_bindings} 个模板绑定，完成 {result.total_rounds} 轮匹配</p>
                  <p>耗时 {formatDuration(result.total_duration_ms)}，{result.termination_reason}</p>
                </div>
              )}
            </div>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-lg text-gray-600">正在匹配模板...</span>
            </div>
          ) : result ? (
            <div className="space-y-6">
              {/* 汇总卡片 */}
              <BatchMatchingSummaryCard result={result} />

              {/* 统计概览 */}
              <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="w-5 h-5 text-green-600" />
                    <span className="text-sm font-medium text-green-800">成功</span>
                  </div>
                  <p className="text-2xl font-bold text-green-900">{result.successful_matches}</p>
                </div>

                <div className="bg-red-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <XCircle className="w-5 h-5 text-red-600" />
                    <span className="text-sm font-medium text-red-800">失败</span>
                  </div>
                  <p className="text-2xl font-bold text-red-900">{result.failed_matches}</p>
                </div>

                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <Target className="w-5 h-5 text-blue-600" />
                    <span className="text-sm font-medium text-blue-800">成功率</span>
                  </div>
                  <p className="text-2xl font-bold text-blue-900">{successRate}%</p>
                </div>

                <div className="bg-purple-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <Clock className="w-5 h-5 text-purple-600" />
                    <span className="text-sm font-medium text-purple-800">总耗时</span>
                  </div>
                  <p className="text-lg font-bold text-purple-900">{formatDuration(result.total_duration_ms)}</p>
                </div>

                <div className="bg-indigo-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <TrendingUp className="w-5 h-5 text-indigo-600" />
                    <span className="text-sm font-medium text-indigo-800">总轮数</span>
                  </div>
                  <p className="text-2xl font-bold text-indigo-900">{result.total_rounds}</p>
                </div>

                <div className="bg-cyan-50 p-4 rounded-lg">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="w-5 h-5 text-cyan-600" />
                    <span className="text-sm font-medium text-cyan-800">成功轮数</span>
                  </div>
                  <p className="text-2xl font-bold text-cyan-900">{result.successful_rounds}</p>
                </div>
              </div>

              {/* 汇总信息 */}
              <div className="bg-gray-50 p-4 rounded-lg">
                <h3 className="text-lg font-medium text-gray-900 mb-3">匹配汇总</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div className="flex items-center space-x-2">
                    <Film className="w-4 h-4 text-gray-600" />
                    <span className="text-gray-600">匹配片段:</span>
                    <span className="font-medium">{result.summary.total_segments_matched}</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Target className="w-4 h-4 text-gray-600" />
                    <span className="text-gray-600">使用素材:</span>
                    <span className="font-medium">{result.summary.total_materials_used}</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Users className="w-4 h-4 text-gray-600" />
                    <span className="text-gray-600">使用模特:</span>
                    <span className="font-medium">{result.summary.total_models_used}</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <TrendingUp className="w-4 h-4 text-gray-600" />
                    <span className="text-gray-600">平均成功率:</span>
                    <span className="font-medium">{(result.summary.average_success_rate * 100).toFixed(1)}%</span>
                  </div>
                </div>
                
                {(result.summary.best_matching_template || result.summary.worst_matching_template) && (
                  <div className="mt-3 pt-3 border-t border-gray-200">
                    {result.summary.best_matching_template && (
                      <div className="flex items-center space-x-2 text-sm">
                        <TrendingUp className="w-4 h-4 text-green-600" />
                        <span className="text-gray-600">最佳匹配模板:</span>
                        <span className="font-medium text-green-800">{result.summary.best_matching_template}</span>
                      </div>
                    )}
                    {result.summary.worst_matching_template && (
                      <div className="flex items-center space-x-2 text-sm mt-1">
                        <TrendingDown className="w-4 h-4 text-red-600" />
                        <span className="text-gray-600">最差匹配模板:</span>
                        <span className="font-medium text-red-800">{result.summary.worst_matching_template}</span>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 详细结果列表 */}
              <div>
                <h3 className="text-lg font-medium text-gray-900 mb-3">详细结果</h3>
                <div className="space-y-3">
                  {result.matching_results.map((item: BatchMatchingItemResult) => (
                    <div
                      key={item.binding_id}
                      className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 transition-colors"
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1">
                          <div className="flex items-center space-x-3">
                            <span className="font-medium text-gray-900">{item.template_name}</span>
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getBatchMatchingStatusColor(item.status)}`}>
                              {getBatchMatchingStatusDisplay(item.status)}
                            </span>
                            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                              第{item.round_number}轮
                            </span>
                          </div>
                          {item.binding_name && (
                            <p className="text-sm text-gray-600 mt-1">绑定名称: {item.binding_name}</p>
                          )}
                          {item.error_message && (
                            <p className="text-sm text-red-600 mt-1">错误: {item.error_message}</p>
                          )}
                          {item.failure_reason && (
                            <p className="text-sm text-orange-600 mt-1">失败原因: {item.failure_reason}</p>
                          )}
                        </div>
                        <div className="text-right">
                          <p className="text-sm text-gray-600">耗时: {formatDuration(item.duration_ms)}</p>
                          {item.matching_result && (
                            <p className="text-sm text-gray-600">
                              成功率: {Math.min((item.matching_result.statistics?.success_rate * 100 || 0), 100).toFixed(1)}%
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-12">
              <p className="text-gray-500">暂无匹配结果</p>
            </div>
          )}
        </div>

        {/* 底部 */}
        <div className="flex justify-between p-6 border-t border-gray-200">
          <div className="flex space-x-3">
            {result && (
              <>
                <button
                  onClick={() => exportMatchingReport(result)}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                >
                  导出报告
                </button>
                <button
                  onClick={() => copyMatchingSummary(result)}
                  className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors"
                >
                  复制摘要
                </button>
              </>
            )}
          </div>
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition-colors"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
};
