/**
 * 系统状态面板组件
 * 
 * 显示系统整体状态概览，包括环境健康状态、执行队列统计等
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { 
  BarChart3, 
  TrendingUp, 
  Server, 
  Activity, 
  Clock, 
  CheckCircle, 
  XCircle, 
  AlertTriangle,
  Zap,
  Users,
  Database,
  Cpu,
  HardDrive,
  Wifi,
  RefreshCw
} from 'lucide-react';

// 系统统计信息接口
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 SystemStatusPanelProps {
  /** 系统统计信息 */
  systemStats: SystemStatistics;
  /** 刷新间隔（毫秒） */
  refreshInterval?: number;
  /** 刷新回调 */
  onRefresh?: () => void;
}

/**
 * 系统状态面板组件
 */
export const SystemStatusPanel: React.FC<SystemStatusPanelProps> = ({
  systemStats,
  refreshInterval = 5000,
  onRefresh
}) => {
  const [lastUpdateTime, setLastUpdateTime] = useState<Date>(new Date());

  // 自动刷新
  useEffect(() => {
    if (!onRefresh || refreshInterval <= 0) return;

    const interval = setInterval(() => {
      onRefresh();
      setLastUpdateTime(new Date());
    }, refreshInterval);

    return () => clearInterval(interval);
  }, [onRefresh, refreshInterval]);

  // 格式化时间
  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN');
  };

  // 格式化数字
  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
  };

  // 格式化时长
  const formatDuration = (seconds: number) => {
    if (seconds < 60) {
      return `${seconds.toFixed(1)}秒`;
    } else if (seconds < 3600) {
      return `${(seconds / 60).toFixed(1)}分钟`;
    } else {
      return `${(seconds / 3600).toFixed(1)}小时`;
    }
  };

  // 获取健康状态颜色
  const getHealthColor = (healthy: number, total: number) => {
    const ratio = total > 0 ? healthy / total : 0;
    if (ratio >= 0.8) return 'text-green-600';
    if (ratio >= 0.5) return 'text-yellow-600';
    return 'text-red-600';
  };

  // 获取使用率颜色
  const getUsageColor = (percentage: number) => {
    if (percentage < 70) return 'bg-green-500';
    if (percentage < 90) return 'bg-yellow-500';
    return 'bg-red-500';
  };

  // 计算成功率
  const successRate = systemStats.execution_stats.total_executions_today > 0
    ? (systemStats.execution_stats.successful_executions_today / systemStats.execution_stats.total_executions_today) * 100
    : 0;

  // 计算环境健康率
  const environmentHealthRate = systemStats.environment_stats.total_environments > 0
    ? (systemStats.environment_stats.healthy_environments / systemStats.environment_stats.total_environments) * 100
    : 0;

  // 计算容量使用率
  const capacityUsageRate = systemStats.environment_stats.total_capacity > 0
    ? (systemStats.environment_stats.used_capacity / systemStats.environment_stats.total_capacity) * 100
    : 0;

  return (
    <div className="space-y-6">
      {/* 状态面板头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <BarChart3 className="w-6 h-6 text-blue-600" />
          <div>
            <h2 className="text-lg font-medium text-gray-900">
              系统状态概览
            </h2>
            <p className="text-sm text-gray-500">
              最后更新: {formatTime(lastUpdateTime)}
            </p>
          </div>
        </div>

        {onRefresh && (
          <button
            onClick={onRefresh}
            className="px-3 py-1 bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors flex items-center space-x-1"
          >
            <RefreshCw className="w-4 h-4" />
            <span>刷新</span>
          </button>
        )}
      </div>

      {/* 关键指标卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {/* 今日执行统计 */}
        <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">
                {formatNumber(systemStats.execution_stats.total_executions_today)}
              </p>
              <p className="text-xs text-green-600">
                成功率 {successRate.toFixed(1)}%
              </p>
            </div>
            <Activity 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">
                {systemStats.execution_stats.current_queue_size}
              </p>
              <p className="text-xs text-blue-600">
                活跃 {systemStats.execution_stats.active_executions}
              </p>
            </div>
            <Clock 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">
                {systemStats.environment_stats.healthy_environments}/{systemStats.environment_stats.total_environments}
              </p>
              <p className={`text-xs ${getHealthColor(systemStats.environment_stats.healthy_environments, systemStats.environment_stats.total_environments)}`}>
                健康率 {environmentHealthRate.toFixed(1)}%
              </p>
            </div>
            <Server 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">
                {systemStats.performance_metrics.average_response_time_ms}ms
              </p>
              <p className="text-xs text-purple-600">
                {systemStats.performance_metrics.requests_per_minute}/分钟
              </p>
            </div>
            <Zap className="w-8 h-8 text-purple-500" />
          </div>
        </div>
      </div>

      {/* 详细统计 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 执行统计详情 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center space-x-2">
            <TrendingUp className="w-5 h-5" />
            <span>执行统计</span>
          </h3>
          
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">成功执行</span>
              <div className="flex items-center space-x-2">
                <CheckCircle className="w-4 h-4 text-green-500" />
                <span className="text-sm font-medium text-gray-900">
                  {formatNumber(systemStats.execution_stats.successful_executions_today)}
                </span>
              </div>
            </div>
            
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">失败执行</span>
              <div className="flex items-center space-x-2">
                <XCircle className="w-4 h-4 text-red-500" />
                <span className="text-sm font-medium text-gray-900">
                  {formatNumber(systemStats.execution_stats.failed_executions_today)}
                </span>
              </div>
            </div>
            
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">平均执行时间</span>
              <span className="text-sm font-medium text-gray-900">
                {formatDuration(systemStats.execution_stats.average_execution_time_seconds)}
              </span>
            </div>
            
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">错误率</span>
              <span className={`text-sm font-medium ${
                systemStats.performance_metrics.error_rate_percent < 5 
                  ? 'text-green-600' 
                  : systemStats.performance_metrics.error_rate_percent < 10
                  ? 'text-yellow-600'
                  : 'text-red-600'
              }`}>
                {systemStats.performance_metrics.error_rate_percent.toFixed(2)}%
              </span>
            </div>
          </div>
        </div>

        {/* 系统资源 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center space-x-2">
            <Cpu className="w-5 h-5" />
            <span>系统资源</span>
          </h3>
          
          <div className="space-y-4">
            {/* CPU使用率 */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm text-gray-600">CPU使用率</span>
                <span className="text-sm font-medium text-gray-900">
                  {systemStats.system_resources.cpu_usage_percent.toFixed(1)}%
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className={`h-2 rounded-full transition-all duration-300 ${getUsageColor(systemStats.system_resources.cpu_usage_percent)}`}
                  style={{ width: `${systemStats.system_resources.cpu_usage_percent}%` }}
                />
              </div>
            </div>

            {/* 内存使用率 */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm text-gray-600">内存使用率</span>
                <span className="text-sm font-medium text-gray-900">
                  {systemStats.system_resources.memory_usage_percent.toFixed(1)}%
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className={`h-2 rounded-full transition-all duration-300 ${getUsageColor(systemStats.system_resources.memory_usage_percent)}`}
                  style={{ width: `${systemStats.system_resources.memory_usage_percent}%` }}
                />
              </div>
            </div>

            {/* 磁盘使用率 */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <span className="text-sm text-gray-600">磁盘使用率</span>
                <span className="text-sm font-medium text-gray-900">
                  {systemStats.system_resources.disk_usage_percent.toFixed(1)}%
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className={`h-2 rounded-full transition-all duration-300 ${getUsageColor(systemStats.system_resources.disk_usage_percent)}`}
                  style={{ width: `${systemStats.system_resources.disk_usage_percent}%` }}
                />
              </div>
            </div>

            {/* 网络状态 */}
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">网络状态</span>
              <div className="flex items-center space-x-2">
                <Wifi className={`w-4 h-4 ${
                  systemStats.system_resources.network_status === 'connected' 
                    ? 'text-green-500' 
                    : systemStats.system_resources.network_status === 'limited'
                    ? 'text-yellow-500'
                    : 'text-red-500'
                }`} />
                <span className="text-sm font-medium text-gray-900">
                  {systemStats.system_resources.network_status === 'connected' 
                    ? '正常' 
                    : systemStats.system_resources.network_status === 'limited'
                    ? '受限'
                    : '断开'}
                </span>
              </div>
            </div>

            {/* 系统运行时间 */}
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">运行时间</span>
              <span className="text-sm font-medium text-gray-900">
                {formatDuration(systemStats.performance_metrics.uptime_hours * 3600)}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* 容量使用情况 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center space-x-2">
          <HardDrive className="w-5 h-5" />
          <span>执行容量</span>
        </h3>
        
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-gray-600">
            已使用 {systemStats.environment_stats.used_capacity} / {systemStats.environment_stats.total_capacity} 个执行槽位
          </span>
          <span className="text-sm font-medium text-gray-900">
            {capacityUsageRate.toFixed(1)}%
          </span>
        </div>
        
        <div className="w-full bg-gray-200 rounded-full h-3">
          <div 
            className={`h-3 rounded-full transition-all duration-300 ${getUsageColor(capacityUsageRate)}`}
            style={{ width: `${capacityUsageRate}%` }}
          />
        </div>
        
        <div className="flex items-center justify-between mt-2 text-xs text-gray-500">
          <span>空闲: {systemStats.environment_stats.total_capacity - systemStats.environment_stats.used_capacity}</span>
          <span>总容量: {systemStats.environment_stats.total_capacity}</span>
        </div>
      </div>
    </div>
  );
};
