/**
 * 监控仪表板组件
 * 
 * 综合的监控界面，包含执行监控器和系统状态面板
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { ExecutionMonitor } from './ExecutionMonitor';
import { SystemStatusPanel } from './SystemStatusPanel';

// 执行状态枚举
type ExecutionStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';

// 执行记录接口
interface WorkflowExecutionRecord {
  id: number;
  workflow_template_id: number;
  workflow_name: string;
  workflow_version: string;
  execution_environment_id?: number;
  execution_environment_name?: string;
  input_data_json: any;
  output_data_json?: any;
  status: ExecutionStatus;
  progress: number;
  comfyui_prompt_id?: string;
  comfyui_workflow_name?: string;
  started_at?: string;
  completed_at?: string;
  duration_seconds?: number;
  error_message?: string;
  error_details_json?: any;
  user_id?: string;
  session_id?: string;
  metadata_json?: any;
  tags?: string[];
  created_at: string;
  updated_at: string;
}

// 执行历史分页响应接口
interface ExecutionHistoryResponse {
  records: WorkflowExecutionRecord[];
  total_count: number;
  page: number;
  page_size: number;
  total_pages: number;
}

// 系统统计信息接口
interface SystemStatistics {
  execution_stats: {
    total_executions_today: number;
    successful_executions_today: number;
    failed_executions_today: number;
    average_execution_time_seconds: number;
    current_queue_size: number;
    active_executions: number;
  };
  
  environment_stats: {
    total_environments: number;
    healthy_environments: number;
    unhealthy_environments: number;
    average_response_time_ms: number;
    total_capacity: number;
    used_capacity: number;
  };
  
  system_resources: {
    cpu_usage_percent: number;
    memory_usage_percent: number;
    disk_usage_percent: number;
    network_status: 'connected' | 'disconnected' | 'limited';
  };
  
  performance_metrics: {
    requests_per_minute: number;
    average_response_time_ms: number;
    error_rate_percent: number;
    uptime_hours: number;
  };
}

// 组件属性接口
interface MonitoringDashboardProps {
  /** 查看执行详情回调 */
  onViewExecutionDetails?: (record: WorkflowExecutionRecord) => void;
  /** 自动刷新间隔（毫秒） */
  refreshInterval?: number;
}

/**
 * 监控仪表板组件
 */
export const MonitoringDashboard: React.FC<MonitoringDashboardProps> = ({
  onViewExecutionDetails,
  refreshInterval = 3000
}) => {
  const [activeExecutions, setActiveExecutions] = useState<WorkflowExecutionRecord[]>([]);
  const [systemStats, setSystemStats] = useState<SystemStatistics>({
    execution_stats: {
      total_executions_today: 0,
      successful_executions_today: 0,
      failed_executions_today: 0,
      average_execution_time_seconds: 0,
      current_queue_size: 0,
      active_executions: 0
    },
    environment_stats: {
      total_environments: 0,
      healthy_environments: 0,
      unhealthy_environments: 0,
      average_response_time_ms: 0,
      total_capacity: 0,
      used_capacity: 0
    },
    system_resources: {
      cpu_usage_percent: 0,
      memory_usage_percent: 0,
      disk_usage_percent: 0,
      network_status: 'connected'
    },
    performance_metrics: {
      requests_per_minute: 0,
      average_response_time_ms: 0,
      error_rate_percent: 0,
      uptime_hours: 0
    }
  });
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 加载活跃执行
  const loadActiveExecutions = useCallback(async () => {
    try {
      const result = await invoke<ExecutionHistoryResponse>('get_execution_history', {
        filter: {
          status: 'running' // 只获取正在执行的
        },
        limit: 50,
        offset: 0
      });

      // 同时获取等待中的执行
      const pendingResult = await invoke<ExecutionHistoryResponse>('get_execution_history', {
        filter: {
          status: 'pending'
        },
        limit: 50,
        offset: 0
      });

      setActiveExecutions([...result.records, ...pendingResult.records]);
    } catch (err) {
      console.error('加载活跃执行失败:', err);
      // 使用模拟数据
      setActiveExecutions([]);
    }
  }, []);

  // 加载系统统计
  const loadSystemStats = useCallback(async () => {
    try {
      const result = await invoke<SystemStatistics>('get_system_statistics');
      setSystemStats(result);
    } catch (err) {
      console.error('加载系统统计失败:', err);

      // 如果API调用失败，使用基础的模拟数据作为后备
      const fallbackStats: SystemStatistics = {
        execution_stats: {
          total_executions_today: 0,
          successful_executions_today: 0,
          failed_executions_today: 0,
          average_execution_time_seconds: 0,
          current_queue_size: activeExecutions.filter(e => e.status === 'pending').length,
          active_executions: activeExecutions.filter(e => e.status === 'running').length
        },
        environment_stats: {
          total_environments: 0,
          healthy_environments: 0,
          unhealthy_environments: 0,
          average_response_time_ms: 0,
          total_capacity: 0,
          used_capacity: activeExecutions.filter(e => e.status === 'running').length
        },
        system_resources: {
          cpu_usage_percent: 0,
          memory_usage_percent: 0,
          disk_usage_percent: 0,
          network_status: 'disconnected'
        },
        performance_metrics: {
          requests_per_minute: 0,
          average_response_time_ms: 0,
          error_rate_percent: 0,
          uptime_hours: 0
        }
      };

      setSystemStats(fallbackStats);
    }
  }, [activeExecutions]);

  // 刷新所有数据
  const refreshData = useCallback(async () => {
    setError(null);
    try {
      await Promise.all([
        loadActiveExecutions(),
        loadSystemStats()
      ]);
    } catch (err) {
      setError('刷新数据失败');
    } finally {
      setLoading(false);
    }
  }, [loadActiveExecutions, loadSystemStats]);

  // 初始加载
  useEffect(() => {
    refreshData();
  }, [refreshData]);

  // 处理取消执行
  const handleCancelExecution = async (executionId: number) => {
    try {
      await invoke('cancel_execution', { executionId });
      // 刷新数据
      await loadActiveExecutions();
    } catch (err) {
      console.error('取消执行失败:', err);
    }
  };

  // 处理查看日志
  const handleViewLogs = async (executionId: number) => {
    try {
      // TODO: 实现查看日志功能
      console.log('查看执行日志:', executionId);
    } catch (err) {
      console.error('查看日志失败:', err);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载监控数据...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center justify-between">
          <span className="text-red-700">{error}</span>
          <button
            onClick={refreshData}
            className="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* 系统状态面板 */}
      <SystemStatusPanel
        systemStats={systemStats}
        refreshInterval={refreshInterval}
        onRefresh={refreshData}
      />

      {/* 执行监控器 */}
      <ExecutionMonitor
        activeExecutions={activeExecutions}
        onCancel={handleCancelExecution}
        onViewLogs={handleViewLogs}
        onViewDetails={onViewExecutionDetails}
        onRefresh={loadActiveExecutions}
        refreshInterval={refreshInterval}
      />
    </div>
  );
};
