/**
 * 重试管理器组件
 * 
 * 提供智能重试策略和批量重试功能
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { 
  RefreshCw, 
  Play, 
  Pause, 
  Square, 
  Settings, 
  Clock, 
  TrendingUp,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Zap,
  Timer,
  BarChart3
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

// 重试策略枚举
type RetryStrategy = 'immediate' | 'exponential' | 'fixed_interval' | 'smart';

// 重试状态枚举
type RetryStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';

// 重试配置接口
interface RetryConfig {
  strategy: RetryStrategy;
  max_attempts: number;
  initial_delay_seconds: number;
  max_delay_seconds: number;
  backoff_multiplier: number;
  timeout_seconds: number;
  retry_on_errors: string[];
  stop_on_errors: string[];
}

// 重试任务接口
interface RetryTask {
  id: number;
  execution_id: number;
  workflow_name: string;
  original_error: string;
  retry_config: RetryConfig;
  status: RetryStatus;
  current_attempt: number;
  next_retry_at?: string;
  started_at: string;
  completed_at?: string;
  success: boolean;
  final_error?: string;
}

// 重试统计接口
interface RetryStatistics {
  total_retries: number;
  successful_retries: number;
  failed_retries: number;
  success_rate: number;
  average_attempts: number;
  most_retried_workflows: Array<{ workflow_name: string; count: number }>;
}

// 组件属性接口
interface RetryManagerProps {
  /** 重试任务列表 */
  retryTasks?: RetryTask[];
  /** 重试统计信息 */
  statistics?: RetryStatistics;
  /** 开始重试回调 */
  onStartRetry?: (executionId: number, config: RetryConfig) => void;
  /** 取消重试回调 */
  onCancelRetry?: (taskId: number) => void;
  /** 批量重试回调 */
  onBatchRetry?: (executionIds: number[], config: RetryConfig) => void;
}

/**
 * 重试管理器组件
 */
export const RetryManager: React.FC<RetryManagerProps> = ({
  retryTasks = [],
  statistics,
  onStartRetry,
  onCancelRetry,
  onBatchRetry
}) => {
  const [selectedTasks, setSelectedTasks] = useState<Set<number>>(new Set());
  const [showConfigModal, setShowConfigModal] = useState(false);
  const [retryConfig, setRetryConfig] = useState<RetryConfig>({
    strategy: 'exponential',
    max_attempts: 3,
    initial_delay_seconds: 30,
    max_delay_seconds: 300,
    backoff_multiplier: 2,
    timeout_seconds: 600,
    retry_on_errors: ['network', 'timeout', 'server'],
    stop_on_errors: ['validation']
  });

  // 重试策略配置
  const strategyConfigs = {
    immediate: {
      label: '立即重试',
      description: '失败后立即重试，不等待',
      icon: Zap
    },
    exponential: {
      label: '指数退避',
      description: '每次重试间隔时间呈指数增长',
      icon: TrendingUp
    },
    fixed_interval: {
      label: '固定间隔',
      description: '每次重试间隔时间固定',
      icon: Clock
    },
    smart: {
      label: '智能重试',
      description: '根据错误类型和历史数据智能调整',
      icon: BarChart3
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: RetryStatus) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4 text-yellow-500" />;
      case 'running':
        return <RefreshCw className="w-4 h-4 text-blue-500 animate-spin" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-500" />;
      case 'cancelled':
        return <Square className="w-4 h-4 text-gray-500" />;
      default:
        return <Clock className="w-4 h-4 text-gray-400" />;
    }
  };

  // 获取状态文本
  const getStatusText = (status: RetryStatus) => {
    const statusMap = {
      pending: '等待重试',
      running: '重试中',
      completed: '重试成功',
      failed: '重试失败',
      cancelled: '已取消'
    };
    return statusMap[status] || '未知';
  };

  // 计算下次重试时间
  const getNextRetryTime = (task: RetryTask) => {
    if (!task.next_retry_at) return '-';
    
    const nextTime = new Date(task.next_retry_at);
    const now = new Date();
    const diffMs = nextTime.getTime() - now.getTime();
    
    if (diffMs <= 0) return '即将重试';
    
    const diffSeconds = Math.floor(diffMs / 1000);
    if (diffSeconds < 60) {
      return `${diffSeconds}秒后`;
    } else if (diffSeconds < 3600) {
      return `${Math.floor(diffSeconds / 60)}分钟后`;
    } else {
      return `${Math.floor(diffSeconds / 3600)}小时后`;
    }
  };

  // 处理任务选择
  const handleTaskSelection = (taskId: number, selected: boolean) => {
    const newSelected = new Set(selectedTasks);
    if (selected) {
      newSelected.add(taskId);
    } else {
      newSelected.delete(taskId);
    }
    setSelectedTasks(newSelected);
  };

  // 处理全选
  const handleSelectAll = (selected: boolean) => {
    if (selected) {
      setSelectedTasks(new Set(retryTasks.map(task => task.id)));
    } else {
      setSelectedTasks(new Set());
    }
  };

  // 处理批量重试
  const handleBatchRetry = () => {
    const selectedExecutionIds = retryTasks
      .filter(task => selectedTasks.has(task.id))
      .map(task => task.execution_id);
    
    if (selectedExecutionIds.length > 0 && onBatchRetry) {
      onBatchRetry(selectedExecutionIds, retryConfig);
      setSelectedTasks(new Set());
    }
  };

  // 处理配置保存
  const handleConfigSave = () => {
    setShowConfigModal(false);
    // 配置已更新，可以应用到后续的重试任务
  };

  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_retries}
                </p>
              </div>
              <RefreshCw className="w-8 h-8 text-blue-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.success_rate * 100).toFixed(1)}%
                </p>
              </div>
              <CheckCircle 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-2xl font-semibold text-gray-900">
                  {statistics.average_attempts.toFixed(1)}
                </p>
              </div>
              <BarChart3 className="w-8 h-8 text-purple-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">
                  {retryTasks.filter(task => task.status === 'running' || task.status === 'pending').length}
                </p>
              </div>
              <Timer className="w-8 h-8 text-yellow-500" />
            </div>
          </div>
        </div>
      )}

      {/* 操作栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <h2 className="text-lg font-medium text-gray-900">重试任务</h2>
          
          {selectedTasks.size > 0 && (
            <div className="flex items-center space-x-2">
              <span className="text-sm text-gray-600">
                已选择 {selectedTasks.size} 个任务
              </span>
              <button
                onClick={handleBatchRetry}
                className="px-3 py-1 bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors flex items-center space-x-1"
              >
                <RefreshCw className="w-3 h-3" />
                <span>批量重试</span>
              </button>
              <button
                onClick={() => setSelectedTasks(new Set())}
                className="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
              >
                取消选择
              </button>
            </div>
          )}
        </div>

        <button
          onClick={() => setShowConfigModal(true)}
          className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center space-x-2"
        >
          <Settings className="w-4 h-4" />
          <span>重试配置</span>
        </button>
      </div>

      {/* 重试任务列表 */}
      {retryTasks.length === 0 ? (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
          <RefreshCw 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">
            当前没有正在进行或等待的重试任务
          </p>
        </div>
      ) : (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left">
                    <input
                      type="checkbox"
                      checked={selectedTasks.size === retryTasks.length && retryTasks.length > 0}
                      onChange={(e) => handleSelectAll(e.target.checked)}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                    />
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    工作流
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    重试进度
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    下次重试
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    原始错误
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {retryTasks.map((task) => (
                  <tr key={task.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <input
                        type="checkbox"
                        checked={selectedTasks.has(task.id)}
                        onChange={(e) => handleTaskSelection(task.id, e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm font-medium text-gray-900">
                        {task.workflow_name}
                      </div>
                      <div className="text-sm text-gray-500">
                        执行ID: {task.execution_id}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center space-x-2">
                        {getStatusIcon(task.status)}
                        <span className="text-sm text-gray-900">
                          {getStatusText(task.status)}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {task.current_attempt} / {task.retry_config.max_attempts}
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-1.5 mt-1">
                        <div 
                          className="bg-blue-600 h-1.5 rounded-full"
                          style={{ 
                            width: `${(task.current_attempt / task.retry_config.max_attempts) * 100}%` 
                          }}
                        />
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        {getNextRetryTime(task)}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900 truncate max-w-xs" title={task.original_error}>
                        {task.original_error}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center space-x-2">
                        {(task.status === 'pending' || task.status === 'running') && onCancelRetry && (
                          <button
                            onClick={() => onCancelRetry(task.id)}
                            className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                            title="取消重试"
                          >
                            <Square className="w-4 h-4" />
                          </button>
                        )}
                        
                        {task.status === 'failed' && onStartRetry && (
                          <button
                            onClick={() => onStartRetry(task.execution_id, task.retry_config)}
                            className="p-1 text-gray-400 hover:text-green-600 transition-colors"
                            title="重新开始重试"
                          >
                            <Play className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* 重试配置模态框 */}
      {showConfigModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] flex flex-col">
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">重试配置</h2>
              <button
                onClick={() => setShowConfigModal(false)}
                className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
              >
                <XCircle className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              {/* 重试策略 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  重试策略
                </label>
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(strategyConfigs).map(([strategy, config]) => {
                    const Icon = config.icon;
                    return (
                      <button
                        key={strategy}
                        type="button"
                        onClick={() => setRetryConfig(prev => ({ ...prev, strategy: strategy as RetryStrategy }))}
                        className={`p-3 border-2 rounded-lg text-left transition-all ${
                          retryConfig.strategy === strategy
                            ? 'border-blue-500 bg-blue-50'
                            : 'border-gray-200 hover:border-gray-300'
                        }`}
                      >
                        <div className="flex items-center space-x-2 mb-1">
                          <Icon className="w-4 h-4" />
                          <span className="font-medium text-sm">{config.label}</span>
                        </div>
                        <p className="text-xs text-gray-600">{config.description}</p>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* 重试参数 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    最大重试次数
                  </label>
                  <input
                    type="number"
                    min="1"
                    max="10"
                    value={retryConfig.max_attempts}
                    onChange={(e) => setRetryConfig(prev => ({ 
                      ...prev, 
                      max_attempts: parseInt(e.target.value) || 1 
                    }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    初始延迟 (秒)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={retryConfig.initial_delay_seconds}
                    onChange={(e) => setRetryConfig(prev => ({ 
                      ...prev, 
                      initial_delay_seconds: parseInt(e.target.value) || 0 
                    }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    最大延迟 (秒)
                  </label>
                  <input
                    type="number"
                    min="0"
                    value={retryConfig.max_delay_seconds}
                    onChange={(e) => setRetryConfig(prev => ({ 
                      ...prev, 
                      max_delay_seconds: parseInt(e.target.value) || 0 
                    }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    退避倍数
                  </label>
                  <input
                    type="number"
                    min="1"
                    step="0.1"
                    value={retryConfig.backoff_multiplier}
                    onChange={(e) => setRetryConfig(prev => ({ 
                      ...prev, 
                      backoff_multiplier: parseFloat(e.target.value) || 1 
                    }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              </div>

              {/* 错误类型配置 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  重试的错误类型
                </label>
                <div className="space-y-2">
                  {['network', 'timeout', 'memory', 'server', 'unknown'].map((errorType) => (
                    <label key={errorType} className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={retryConfig.retry_on_errors.includes(errorType)}
                        onChange={(e) => {
                          const newErrors = e.target.checked
                            ? [...retryConfig.retry_on_errors, errorType]
                            : retryConfig.retry_on_errors.filter(t => t !== errorType);
                          setRetryConfig(prev => ({ ...prev, retry_on_errors: newErrors }));
                        }}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-sm text-gray-700">{errorType}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>

            <div className="flex items-center justify-end space-x-3 p-6 border-t border-gray-200">
              <button
                onClick={() => setShowConfigModal(false)}
                className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleConfigSave}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                保存配置
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
