/**
 * 错误分析器组件
 * 
 * 分析和展示工作流执行错误，提供错误分类和解决建议
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { 
  AlertTriangle, 
  XCircle, 
  RefreshCw, 
  Search, 
  Filter,
  TrendingUp,
  Clock,
  Code,
  Server,
  Wifi,
  HardDrive,
  Zap,
  ChevronDown,
  ChevronRight,
  Copy,
  ExternalLink
} from 'lucide-react';

// 错误类型枚举
type ErrorType = 'network' | 'timeout' | 'memory' | 'validation' | 'server' | 'unknown';

// 错误严重程度枚举
type ErrorSeverity = 'low' | 'medium' | 'high' | 'critical';

// 错误记录接口
interface ErrorRecord {
  id: number;
  execution_id: number;
  workflow_name: string;
  error_type: ErrorType;
  severity: ErrorSeverity;
  error_message: string;
  error_details: any;
  stack_trace?: string;
  environment_name?: string;
  occurred_at: string;
  resolved: boolean;
  resolution_notes?: string;
}

// 错误统计接口
interface ErrorStatistics {
  total_errors: number;
  errors_by_type: Record<ErrorType, number>;
  errors_by_severity: Record<ErrorSeverity, number>;
  error_rate_trend: Array<{ date: string; count: number }>;
  most_common_errors: Array<{ message: string; count: number }>;
  resolution_rate: number;
}

// 错误解决建议接口
interface ErrorSolution {
  error_type: ErrorType;
  title: string;
  description: string;
  steps: string[];
  prevention_tips: string[];
}

// 组件属性接口
interface ErrorAnalyzerProps {
  /** 错误记录列表 */
  errors?: ErrorRecord[];
  /** 错误统计信息 */
  statistics?: ErrorStatistics;
  /** 标记错误已解决回调 */
  onMarkResolved?: (errorId: number, notes: string) => void;
  /** 重试执行回调 */
  onRetryExecution?: (executionId: number) => void;
}

/**
 * 错误分析器组件
 */
export const ErrorAnalyzer: React.FC<ErrorAnalyzerProps> = ({
  errors = [],
  statistics,
  onMarkResolved,
  onRetryExecution
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState<ErrorType | ''>('');
  const [severityFilter, setSeverityFilter] = useState<ErrorSeverity | ''>('');
  const [expandedErrors, setExpandedErrors] = useState<Set<number>>(new Set());
  const [resolutionNotes, setResolutionNotes] = useState<Record<number, string>>({});

  // 错误类型配置
  const errorTypeConfigs = {
    network: {
      icon: Wifi,
      label: '网络错误',
      color: 'text-red-500',
      bgColor: 'bg-red-50',
      borderColor: 'border-red-200'
    },
    timeout: {
      icon: Clock,
      label: '超时错误',
      color: 'text-yellow-500',
      bgColor: 'bg-yellow-50',
      borderColor: 'border-yellow-200'
    },
    memory: {
      icon: HardDrive,
      label: '内存错误',
      color: 'text-purple-500',
      bgColor: 'bg-purple-50',
      borderColor: 'border-purple-200'
    },
    validation: {
      icon: Code,
      label: '验证错误',
      color: 'text-blue-500',
      bgColor: 'bg-blue-50',
      borderColor: 'border-blue-200'
    },
    server: {
      icon: Server,
      label: '服务器错误',
      color: 'text-orange-500',
      bgColor: 'bg-orange-50',
      borderColor: 'border-orange-200'
    },
    unknown: {
      icon: AlertTriangle,
      label: '未知错误',
      color: 'text-gray-500',
      bgColor: 'bg-gray-50',
      borderColor: 'border-gray-200'
    }
  };

  // 严重程度配置
  const severityConfigs = {
    low: { label: '低', color: 'text-green-600', bgColor: 'bg-green-100' },
    medium: { label: '中', color: 'text-yellow-600', bgColor: 'bg-yellow-100' },
    high: { label: '高', color: 'text-orange-600', bgColor: 'bg-orange-100' },
    critical: { label: '严重', color: 'text-red-600', bgColor: 'bg-red-100' }
  };

  // 错误解决方案
  const errorSolutions: Record<ErrorType, ErrorSolution> = {
    network: {
      error_type: 'network',
      title: '网络连接问题',
      description: '执行环境网络连接异常或不稳定',
      steps: [
        '检查网络连接状态',
        '验证执行环境URL是否正确',
        '检查防火墙设置',
        '尝试重新连接执行环境'
      ],
      prevention_tips: [
        '使用稳定的网络连接',
        '配置网络重试机制',
        '监控网络状态'
      ]
    },
    timeout: {
      error_type: 'timeout',
      title: '执行超时',
      description: '工作流执行时间超过预设限制',
      steps: [
        '检查工作流复杂度',
        '增加超时时间限制',
        '优化工作流配置',
        '检查执行环境性能'
      ],
      prevention_tips: [
        '合理设置超时时间',
        '优化工作流性能',
        '监控执行时间趋势'
      ]
    },
    memory: {
      error_type: 'memory',
      title: '内存不足',
      description: '执行过程中内存使用超出限制',
      steps: [
        '检查输入数据大小',
        '增加内存限制',
        '优化数据处理',
        '分批处理大数据'
      ],
      prevention_tips: [
        '监控内存使用情况',
        '合理配置内存限制',
        '优化数据处理算法'
      ]
    },
    validation: {
      error_type: 'validation',
      title: '数据验证失败',
      description: '输入数据不符合工作流要求',
      steps: [
        '检查输入数据格式',
        '验证必填字段',
        '检查数据类型',
        '修正输入数据'
      ],
      prevention_tips: [
        '完善数据验证规则',
        '提供清晰的输入说明',
        '实现前端验证'
      ]
    },
    server: {
      error_type: 'server',
      title: '服务器错误',
      description: '执行环境服务器内部错误',
      steps: [
        '检查服务器状态',
        '查看服务器日志',
        '重启执行环境',
        '联系技术支持'
      ],
      prevention_tips: [
        '定期维护服务器',
        '监控服务器健康状态',
        '配置自动重启机制'
      ]
    },
    unknown: {
      error_type: 'unknown',
      title: '未知错误',
      description: '无法确定具体错误原因',
      steps: [
        '收集详细错误信息',
        '检查系统日志',
        '尝试重新执行',
        '联系技术支持'
      ],
      prevention_tips: [
        '完善错误日志记录',
        '定期更新系统',
        '建立错误监控机制'
      ]
    }
  };

  // 筛选错误
  const filteredErrors = errors.filter(error => {
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      if (!error.error_message.toLowerCase().includes(searchLower) &&
          !error.workflow_name.toLowerCase().includes(searchLower)) {
        return false;
      }
    }
    if (typeFilter && error.error_type !== typeFilter) return false;
    if (severityFilter && error.severity !== severityFilter) return false;
    return true;
  });

  // 切换错误展开状态
  const toggleErrorExpanded = (errorId: number) => {
    const newExpanded = new Set(expandedErrors);
    if (newExpanded.has(errorId)) {
      newExpanded.delete(errorId);
    } else {
      newExpanded.add(errorId);
    }
    setExpandedErrors(newExpanded);
  };

  // 复制错误信息
  const copyErrorInfo = async (error: ErrorRecord) => {
    const errorInfo = `
错误ID: ${error.id}
执行ID: ${error.execution_id}
工作流: ${error.workflow_name}
错误类型: ${errorTypeConfigs[error.error_type].label}
严重程度: ${severityConfigs[error.severity].label}
错误信息: ${error.error_message}
发生时间: ${new Date(error.occurred_at).toLocaleString('zh-CN')}
环境: ${error.environment_name || '未知'}
${error.stack_trace ? `\n堆栈跟踪:\n${error.stack_trace}` : ''}
    `.trim();

    try {
      await navigator.clipboard.writeText(errorInfo);
      // TODO: 显示复制成功提示
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 标记错误已解决
  const handleMarkResolved = (errorId: number) => {
    const notes = resolutionNotes[errorId] || '';
    if (onMarkResolved) {
      onMarkResolved(errorId, notes);
    }
  };

  return (
    <div className="space-y-6">
      {/* 错误统计概览 */}
      {statistics && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">总错误数</p>
                <p className="text-2xl font-semibold text-gray-900">
                  {statistics.total_errors}
                </p>
              </div>
              <XCircle className="w-8 h-8 text-red-500" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">解决率</p>
                <p className="text-2xl font-semibold text-gray-900">
                  {(statistics.resolution_rate * 100).toFixed(1)}%
                </p>
              </div>
              <TrendingUp className="w-8 h-8 text-green-500" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">最常见错误</p>
                <p className="text-sm font-medium text-gray-900 truncate">
                  {statistics.most_common_errors[0]?.message || '无'}
                </p>
                <p className="text-xs text-gray-500">
                  {statistics.most_common_errors[0]?.count || 0} 次
                </p>
              </div>
              <AlertTriangle className="w-8 h-8 text-yellow-500" />
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">严重错误</p>
                <p className="text-2xl font-semibold text-gray-900">
                  {statistics.errors_by_severity.critical || 0}
                </p>
              </div>
              <AlertTriangle className="w-8 h-8 text-red-500" />
            </div>
          </div>
        </div>
      )}

      {/* 筛选和搜索 */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="搜索错误信息或工作流名称..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>

        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value as ErrorType | '')}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
          <option value="">所有类型</option>
          {Object.entries(errorTypeConfigs).map(([type, config]) => (
            <option key={type} value={type}>{config.label}</option>
          ))}
        </select>

        <select
          value={severityFilter}
          onChange={(e) => setSeverityFilter(e.target.value as ErrorSeverity | '')}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
          <option value="">所有严重程度</option>
          {Object.entries(severityConfigs).map(([severity, config]) => (
            <option key={severity} value={severity}>{config.label}</option>
          ))}
        </select>
      </div>

      {/* 错误列表 */}
      {filteredErrors.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
          <AlertTriangle className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无错误记录
          </h3>
          <p className="text-gray-600">
            {searchTerm || typeFilter || severityFilter 
              ? '没有找到匹配的错误记录' 
              : '系统运行正常，没有错误记录'}
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {filteredErrors.map((error) => {
            const typeConfig = errorTypeConfigs[error.error_type];
            const severityConfig = severityConfigs[error.severity];
            const isExpanded = expandedErrors.has(error.id);
            const IconComponent = typeConfig.icon;
            const solution = errorSolutions[error.error_type];

            return (
              <div
                key={error.id}
                className={`bg-white rounded-lg shadow-sm border-2 ${typeConfig.borderColor} ${
                  error.resolved ? 'opacity-60' : ''
                }`}
              >
                {/* 错误头部 */}
                <div className="p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-start space-x-3 flex-1">
                      <IconComponent className={`w-5 h-5 mt-0.5 ${typeConfig.color}`} />
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-1">
                          <h3 className="text-sm font-medium text-gray-900">
                            {error.workflow_name}
                          </h3>
                          <span className={`px-2 py-1 text-xs rounded-full ${severityConfig.bgColor} ${severityConfig.color}`}>
                            {severityConfig.label}
                          </span>
                          <span className={`px-2 py-1 text-xs rounded-full ${typeConfig.bgColor} ${typeConfig.color}`}>
                            {typeConfig.label}
                          </span>
                          {error.resolved && (
                            <span className="px-2 py-1 text-xs rounded-full bg-green-100 text-green-800">
                              已解决
                            </span>
                          )}
                        </div>
                        <p className="text-sm text-gray-700 mb-2">
                          {error.error_message}
                        </p>
                        <div className="flex items-center space-x-4 text-xs text-gray-500">
                          <span>ID: {error.id}</span>
                          <span>执行ID: {error.execution_id}</span>
                          <span>时间: {new Date(error.occurred_at).toLocaleString('zh-CN')}</span>
                          {error.environment_name && (
                            <span>环境: {error.environment_name}</span>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => copyErrorInfo(error)}
                        className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                        title="复制错误信息"
                      >
                        <Copy className="w-4 h-4" />
                      </button>

                      {onRetryExecution && !error.resolved && (
                        <button
                          onClick={() => onRetryExecution(error.execution_id)}
                          className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                          title="重试执行"
                        >
                          <RefreshCw className="w-4 h-4" />
                        </button>
                      )}

                      <button
                        onClick={() => toggleErrorExpanded(error.id)}
                        className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
                        title={isExpanded ? '收起详情' : '展开详情'}
                      >
                        {isExpanded ? (
                          <ChevronDown className="w-4 h-4" />
                        ) : (
                          <ChevronRight className="w-4 h-4" />
                        )}
                      </button>
                    </div>
                  </div>
                </div>

                {/* 错误详情 */}
                {isExpanded && (
                  <div className="border-t border-gray-200 p-4 space-y-4">
                    {/* 错误详细信息 */}
                    {error.error_details && (
                      <div>
                        <h4 className="text-sm font-medium text-gray-900 mb-2">错误详情</h4>
                        <pre className="text-xs text-gray-700 bg-gray-50 p-3 rounded overflow-auto max-h-32">
                          {JSON.stringify(error.error_details, null, 2)}
                        </pre>
                      </div>
                    )}

                    {/* 堆栈跟踪 */}
                    {error.stack_trace && (
                      <div>
                        <h4 className="text-sm font-medium text-gray-900 mb-2">堆栈跟踪</h4>
                        <pre className="text-xs text-gray-700 bg-gray-50 p-3 rounded overflow-auto max-h-32">
                          {error.stack_trace}
                        </pre>
                      </div>
                    )}

                    {/* 解决方案 */}
                    <div>
                      <h4 className="text-sm font-medium text-gray-900 mb-2">解决方案</h4>
                      <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                        <h5 className="text-sm font-medium text-blue-900 mb-1">{solution.title}</h5>
                        <p className="text-sm text-blue-700 mb-2">{solution.description}</p>
                        <div className="space-y-2">
                          <div>
                            <h6 className="text-xs font-medium text-blue-900">解决步骤:</h6>
                            <ul className="text-xs text-blue-700 list-disc list-inside space-y-1">
                              {solution.steps.map((step, index) => (
                                <li key={index}>{step}</li>
                              ))}
                            </ul>
                          </div>
                          <div>
                            <h6 className="text-xs font-medium text-blue-900">预防建议:</h6>
                            <ul className="text-xs text-blue-700 list-disc list-inside space-y-1">
                              {solution.prevention_tips.map((tip, index) => (
                                <li key={index}>{tip}</li>
                              ))}
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* 解决标记 */}
                    {!error.resolved && onMarkResolved && (
                      <div className="bg-gray-50 rounded-lg p-3">
                        <h4 className="text-sm font-medium text-gray-900 mb-2">标记为已解决</h4>
                        <textarea
                          value={resolutionNotes[error.id] || ''}
                          onChange={(e) => setResolutionNotes(prev => ({
                            ...prev,
                            [error.id]: e.target.value
                          }))}
                          placeholder="请输入解决方案或备注..."
                          rows={2}
                          className="w-full px-3 py-2 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        />
                        <button
                          onClick={() => handleMarkResolved(error.id)}
                          className="mt-2 px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700 transition-colors"
                        >
                          标记已解决
                        </button>
                      </div>
                    )}

                    {/* 已解决信息 */}
                    {error.resolved && error.resolution_notes && (
                      <div className="bg-green-50 border border-green-200 rounded-lg p-3">
                        <h4 className="text-sm font-medium text-green-900 mb-1">解决方案</h4>
                        <p className="text-sm text-green-700">{error.resolution_notes}</p>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};
