'use client';

import { useState, useEffect } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { RefreshCw } from 'lucide-react';
import { SystemPerformance } from '@/types/monitor';
import {
  CpuMetricCard,
  MemoryMetricCard,
  DiskMetricCard,
  JvmInfoCard,
  TomcatInfoCard,
  PerformanceTrendChart,
  PerformanceInstructions
} from './components';

// API服务函数
const performanceApi = {
  // 获取当前性能数据
  getCurrentPerformance: async (): Promise<SystemPerformance> => {
    try {
      const response = await fetch('/api/monitor/performance/current');
      if (!response.ok) {
        throw new Error('Failed to fetch performance data');
      }
      return await response.json();
    } catch (error) {
      console.warn('Failed to fetch performance data, using mock data:', error);
      // 如果API调用失败，返回模拟数据
      return getMockPerformanceData();
    }
  },

  // 获取历史性能数据
  getPerformanceHistory: async (limit: number = 20): Promise<SystemPerformance[]> => {
    try {
      const response = await fetch(`/api/monitor/performance/history?limit=${limit}`);
      if (!response.ok) {
        throw new Error('Failed to fetch performance history');
      }
      return await response.json();
    } catch (error) {
      console.warn('Failed to fetch performance history, using mock data:', error);
      // 如果API调用失败，返回模拟历史数据
      return Array.from({ length: Math.min(5, limit) }, (_, i) => {
        const mockData = getMockPerformanceData();
        mockData.timestamp = new Date(Date.now() - (4 - i) * 5000).toISOString();
        return mockData;
      });
    }
  }
};

// 模拟数据生成函数
function getMockPerformanceData(): SystemPerformance {
  const mockData: SystemPerformance = {
    timestamp: new Date().toISOString(),
    cpu: {
      usage: Math.random() * 60 + 20, // 20-80%
      cores: 8,
    },
    memory: {
      total: 16384, // 16GB
      used: Math.random() * 8192 + 4096, // 4-12GB
      free: 0,
      usage: 0,
    },
    disk: {
      total: 512, // 512GB
      used: Math.random() * 102 + 204, // 204-306GB
      free: 0,
      usage: 0,
    },
    jvm: {
      heapUsed: Math.random() * 1024 + 512, // 512-1536MB
      heapMax: 2048, // 2GB
      heapUsage: 0,
      nonHeapUsed: Math.random() * 100 + 50,
      threadCount: Math.floor(Math.random() * 50 + 100),
      gcCount: Math.floor(Math.random() * 10 + 50),
      gcTime: Math.floor(Math.random() * 200 + 100),
    },
    tomcat: {
      threadCount: Math.floor(Math.random() * 50 + 50),
      maxThreads: 200,
      connectionCount: Math.floor(Math.random() * 100 + 50),
      requestCount: Math.floor(Math.random() * 10000 + 50000),
      errorCount: Math.floor(Math.random() * 10),
    },
  };

  // 计算百分比
  mockData.memory.free = mockData.memory.total - mockData.memory.used;
  mockData.memory.usage = (mockData.memory.used / mockData.memory.total) * 100;
  mockData.disk.free = mockData.disk.total - mockData.disk.used;
  mockData.disk.usage = (mockData.disk.used / mockData.disk.total) * 100;
  if (mockData.jvm) {
    mockData.jvm.heapUsage = (mockData.jvm.heapUsed / mockData.jvm.heapMax) * 100;
  }

  return mockData;
}

export default function PerformanceMonitorPage() {
  const [performance, setPerformance] = useState<SystemPerformance | null>(null);
  const [history, setHistory] = useState<SystemPerformance[]>([]);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadPerformance();
    const interval = setInterval(() => {
      if (autoRefresh) {
        loadPerformance();
      }
    }, 5000); // 每5秒刷新一次

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

  const loadPerformance = async () => {
    try {
      setError(null);
      setLoading(true);

      // 获取当前数据
      const currentData = await performanceApi.getCurrentPerformance();

      setPerformance(currentData);

      // 保存历史数据（最多保留20条）
      setHistory(prev => {
        const newHistory = [...prev, currentData].slice(-20);
        return newHistory;
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载性能数据失败');
      console.error('Failed to load performance data:', err);
    } finally {
      setLoading(false);
    }
  };

  const getUsageColor = (usage: number) => {
    if (usage < 60) return 'text-green-600';
    if (usage < 80) return 'text-yellow-600';
    return 'text-red-600';
  };

  const getUsageStatus = (usage: number) => {
    if (usage < 60) return '正常';
    if (usage < 80) return '警告';
    return '危险';
  };

  const formatBytes = (bytes: number) => {
    if (bytes < 1024) return `${bytes.toFixed(2)} MB`;
    return `${(bytes / 1024).toFixed(2)} GB`;
  };

  if (loading && !performance) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <RefreshCw className="w-8 h-8 animate-spin text-green-600 mx-auto mb-2" />
          <p className="text-muted-foreground">正在加载性能数据...</p>
        </div>
      </div>
    );
  }

  if (error && !performance) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-red-600 mb-4">加载失败: {error}</p>
          <Button onClick={loadPerformance} variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            重试
          </Button>
        </div>
      </div>
    );
  }

  if (!performance) {
    return null;
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和控制按钮 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">性能监控</h2>
          <p className="text-muted-foreground">实时监控系统运行健康状态</p>
        </div>
        <div className="flex items-center gap-2">
          <Badge variant={autoRefresh ? 'default' : 'outline'}>
            {autoRefresh ? '自动刷新' : '已暂停'}
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setAutoRefresh(!autoRefresh)}
          >
            {autoRefresh ? '暂停' : '启动'}
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={loadPerformance}
            disabled={loading}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        </div>
      </div>

      {error && (
        <div className="p-4 border border-yellow-200 bg-yellow-50 rounded-md">
          <p className="text-yellow-800 text-sm">
            警告: {error} (当前显示为模拟数据)
          </p>
        </div>
      )}

      {/* CPU和内存卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <CpuMetricCard
          performance={performance}
          getUsageColor={getUsageColor}
          getUsageStatus={getUsageStatus}
        />
        <MemoryMetricCard
          performance={performance}
          getUsageColor={getUsageColor}
          getUsageStatus={getUsageStatus}
          formatBytes={formatBytes}
        />
      </div>

      {/* 磁盘卡片 */}
      <DiskMetricCard
        performance={performance}
        getUsageColor={getUsageColor}
        getUsageStatus={getUsageStatus}
        formatBytes={formatBytes}
      />

      {/* JVM信息卡片 */}
      <JvmInfoCard
        performance={performance}
        formatBytes={formatBytes}
      />

      {/* Tomcat信息卡片 */}
      <TomcatInfoCard
        performance={performance}
      />

      {/* 性能趋势图 */}
      <PerformanceTrendChart
        history={history}
      />

      {/* 使用说明 */}
      <PerformanceInstructions />
    </div>
  );
}