import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Progress } from '../ui/progress';
import { Badge } from '../ui/badge';
import { SystemPerformance } from '../../types/monitor';
import { Activity, Cpu, HardDrive, MemoryStick, Server, RefreshCw } from 'lucide-react';
import { Button } from '../ui/button';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

export function PerformanceMonitor() {
  const [performance, setPerformance] = useState<SystemPerformance | null>(null);
  const [history, setHistory] = useState<SystemPerformance[]>([]);
  const [autoRefresh, setAutoRefresh] = useState(true);

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

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

  const loadPerformance = () => {
    // 模拟性能数据
    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;
    }

    setPerformance(mockData);
    
    // 保存历史数据（最多保留20条）
    setHistory(prev => {
      const newHistory = [...prev, mockData].slice(-20);
      return newHistory;
    });
  };

  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 (!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>
    );
  }

  const chartData = history.map((item, index) => ({
    time: new Date(item.timestamp).toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit', 
      second: '2-digit' 
    }),
    CPU: item.cpu.usage.toFixed(1),
    内存: item.memory.usage.toFixed(1),
    磁盘: item.disk.usage.toFixed(1),
  }));

  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}
          >
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新
          </Button>
        </div>
      </div>

      {/* CPU和内存 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Cpu className="w-5 h-5 text-blue-600" />
              <h3>CPU使用率</h3>
            </div>
            <Badge className={getUsageColor(performance.cpu.usage)}>
              {getUsageStatus(performance.cpu.usage)}
            </Badge>
          </div>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm text-muted-foreground">使用率</span>
              <span className={`${getUsageColor(performance.cpu.usage)}`}>
                {performance.cpu.usage.toFixed(1)}%
              </span>
            </div>
            <Progress value={performance.cpu.usage} className="h-2" />
            <div className="flex items-center justify-between text-sm">
              <span className="text-muted-foreground">核心数</span>
              <span>{performance.cpu.cores} 核</span>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <MemoryStick className="w-5 h-5 text-green-600" />
              <h3>内存使用率</h3>
            </div>
            <Badge className={getUsageColor(performance.memory.usage)}>
              {getUsageStatus(performance.memory.usage)}
            </Badge>
          </div>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm text-muted-foreground">使用率</span>
              <span className={getUsageColor(performance.memory.usage)}>
                {performance.memory.usage.toFixed(1)}%
              </span>
            </div>
            <Progress value={performance.memory.usage} className="h-2" />
            <div className="grid grid-cols-2 gap-2 text-sm">
              <div>
                <span className="text-muted-foreground">已用</span>
                <p>{formatBytes(performance.memory.used)}</p>
              </div>
              <div>
                <span className="text-muted-foreground">总量</span>
                <p>{formatBytes(performance.memory.total)}</p>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* 磁盘 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <HardDrive className="w-5 h-5 text-purple-600" />
            <h3>磁盘使用率</h3>
          </div>
          <Badge className={getUsageColor(performance.disk.usage)}>
            {getUsageStatus(performance.disk.usage)}
          </Badge>
        </div>
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">使用率</span>
            <span className={getUsageColor(performance.disk.usage)}>
              {performance.disk.usage.toFixed(1)}%
            </span>
          </div>
          <Progress value={performance.disk.usage} className="h-2" />
          <div className="grid grid-cols-3 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground">已用</span>
              <p>{formatBytes(performance.disk.used)}</p>
            </div>
            <div>
              <span className="text-muted-foreground">可用</span>
              <p>{formatBytes(performance.disk.free)}</p>
            </div>
            <div>
              <span className="text-muted-foreground">总量</span>
              <p>{formatBytes(performance.disk.total)}</p>
            </div>
          </div>
        </div>
      </Card>

      {/* JVM信息 */}
      {performance.jvm && (
        <Card className="p-6">
          <div className="flex items-center gap-2 mb-4">
            <Server className="w-5 h-5 text-orange-600" />
            <h3>JVM信息</h3>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-muted-foreground">堆内存使用</p>
              <p className="mt-1">{performance.jvm.heapUsage.toFixed(1)}%</p>
              <Progress value={performance.jvm.heapUsage} className="h-1 mt-2" />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">堆内存</p>
              <p className="mt-1">
                {formatBytes(performance.jvm.heapUsed)} / {formatBytes(performance.jvm.heapMax)}
              </p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">非堆内存</p>
              <p className="mt-1">{formatBytes(performance.jvm.nonHeapUsed)}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">线程数</p>
              <p className="mt-1">{performance.jvm.threadCount}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">GC次数</p>
              <p className="mt-1">{performance.jvm.gcCount}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">GC耗时</p>
              <p className="mt-1">{performance.jvm.gcTime}ms</p>
            </div>
          </div>
        </Card>
      )}

      {/* Tomcat信息 */}
      {performance.tomcat && (
        <Card className="p-6">
          <div className="flex items-center gap-2 mb-4">
            <Activity className="w-5 h-5 text-red-600" />
            <h3>Tomcat信息</h3>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            <div>
              <p className="text-sm text-muted-foreground">线程数</p>
              <p className="mt-1">
                {performance.tomcat.threadCount} / {performance.tomcat.maxThreads}
              </p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">连接数</p>
              <p className="mt-1">{performance.tomcat.connectionCount}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">请求数</p>
              <p className="mt-1">{performance.tomcat.requestCount.toLocaleString()}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">错误数</p>
              <p className="mt-1 text-red-600">{performance.tomcat.errorCount}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">错误率</p>
              <p className="mt-1">
                {((performance.tomcat.errorCount / performance.tomcat.requestCount) * 100).toFixed(2)}%
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* 趋势图 */}
      {history.length > 1 && (
        <Card className="p-6">
          <h3 className="mb-4">性能趋势</h3>
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={chartData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="time" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line type="monotone" dataKey="CPU" stroke="#3b82f6" strokeWidth={2} />
              <Line type="monotone" dataKey="内存" stroke="#10b981" strokeWidth={2} />
              <Line type="monotone" dataKey="磁盘" stroke="#a855f7" strokeWidth={2} />
            </LineChart>
          </ResponsiveContainer>
        </Card>
      )}

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <Activity className="w-4 h-4 inline mr-2" />
          性能监控说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 系统每5秒自动刷新一次性能数据</li>
          <li>• 使用率超过60%显示警告，超过80%显示危险</li>
          <li>• 趋势图显示最近20次的性能数据变化</li>
          <li>• 建议在性能使用率持续偏高时进行系统优化</li>
          <li>• JVM和Tomcat信息仅在Java环境下可用</li>
        </ul>
      </Card>
    </div>
  );
}
