import { useEffect, useState } from "react"
import { Cpu, Database, Activity, ChevronLeft, ChevronRight } from "lucide-react"

interface SystemStats {
  memory: {
    rss: number
    heapTotal: number
    heapUsed: number
  }
  uptime: number
  activeBots: number
}

export function SystemMonitor() {
  const [stats, setStats] = useState<SystemStats | null>(null)
  const [collapsed, setCollapsed] = useState(true)

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch('/api/system/stats')
        if (response.ok) {
          const data = await response.json()
          setStats(data)
        }
      } catch (error) {
        console.error('Failed to fetch system stats:', error)
      }
    }

    fetchStats()
    const interval = setInterval(fetchStats, 5000) // Update every 5s
    return () => clearInterval(interval)
  }, [])

  if (!stats) {
    return (
      <div className="fixed bottom-4 right-4 z-50 bg-white/80 backdrop-blur-md border border-white/50 shadow-lg rounded-2xl p-3 flex items-center gap-2 text-xs font-medium text-slate-500">
        <Activity className="h-3 w-3 animate-spin" />
        <span>Loading stats...</span>
      </div>
    )
  }

  return (
    <div
      className={`fixed bottom-4 right-4 z-50 bg-white/80 backdrop-blur-md border border-white/50 shadow-lg rounded-2xl text-xs font-medium text-slate-600 transition-all hover:opacity-100 opacity-70 overflow-hidden h-20 ${collapsed ? "w-8" : "w-56"}`}
    >
      <button
        className="absolute right-1 top-1/2 -translate-y-1/2 h-6 w-6 rounded-full bg-white/80 border border-white/70 text-slate-500 hover:text-slate-700 transition"
        onClick={() => setCollapsed(prev => !prev)}
        title={collapsed ? "展开" : "收起"}
      >
        {collapsed ? <ChevronLeft className="h-4 w-4 mx-auto" /> : <ChevronRight className="h-4 w-4 mx-auto" />}
      </button>
      <div className={`p-3 flex flex-col gap-2 transition-all ${collapsed ? "opacity-0 pointer-events-none -translate-x-2" : "opacity-100"}`}>
        <div className="flex items-center gap-2" title="系统运行时间">
          <Activity className="h-3 w-3 text-blue-500" />
          <span>运行时间: {formatUptime(stats.uptime)}</span>
        </div>
        <div className="flex items-center gap-2" title={`总占用: ${stats.memory.rss}MB | JS对象: ${stats.memory.heapUsed}MB`}>
          <Database className="h-3 w-3 text-purple-500" />
          <span>内存: {stats.memory.rss} MB (堆: {stats.memory.heapUsed} MB)</span>
        </div>
        <div className="flex items-center gap-2" title="当前在线挂机账号数">
          <Cpu className="h-3 w-3 text-green-500" />
          <span>挂机数量: {stats.activeBots}</span>
        </div>
      </div>
    </div>
  )
}

function formatUptime(seconds: number) {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  return `${h}h ${m}m ${s}s`
}
