"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { ArrowLeft, Server, CheckCircle2, AlertTriangle, RefreshCw, Clock } from "lucide-react"
import Link from "next/link"
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"

const performanceData = [
  { time: "5m", p50: 32, p95: 85, p99: 120 },
  { time: "10m", p50: 35, p95: 88, p99: 125 },
  { time: "15m", p50: 30, p95: 82, p99: 115 },
  { time: "20m", p50: 38, p95: 92, p99: 135 },
  { time: "25m", p50: 33, p95: 86, p99: 122 },
  { time: "30m", p50: 31, p95: 84, p99: 118 },
]

const healthChecks = [
  { name: "数据库连接池", status: "healthy", value: "48/50", description: "活跃连接数" },
  { name: "Redis缓存", status: "healthy", value: "99.9%", description: "命中率" },
  { name: "消息队列", status: "healthy", value: "0", description: "积压消息" },
  { name: "定时任务", status: "healthy", value: "12/12", description: "运行中任务" },
  { name: "外部API", status: "degraded", value: "95.2%", description: "成功率" },
  { name: "文件存储", status: "healthy", value: "1.6TB", description: "已使用" },
]

const nodeStatus = [
  { id: 1, name: "node-01", role: "Master", cpu: 62, memory: 68, status: "healthy" },
  { id: 2, name: "node-02", role: "Worker", cpu: 55, memory: 72, status: "healthy" },
  { id: 3, name: "node-03", role: "Worker", cpu: 48, memory: 65, status: "healthy" },
  { id: 4, name: "node-04", role: "Worker", cpu: 71, memory: 78, status: "degraded" },
]

export default function HealthPage() {
  const [overallHealth, setOverallHealth] = useState(98.5)

  useEffect(() => {
    const interval = setInterval(() => {
      setOverallHealth((prev) => Math.min(100, Math.max(95, prev + (Math.random() - 0.5) * 1)))
    }, 5000)
    return () => clearInterval(interval)
  }, [])

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-emerald-50/30 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/monitoring">
              <Button variant="ghost" size="icon" className="rounded-full">
                <ArrowLeft className="w-5 h-5" />
              </Button>
            </Link>
            <div>
              <h1 className="text-2xl font-bold text-slate-800">系统健康度</h1>
              <p className="text-slate-500 mt-1">服务状态、性能指标与集群监控</p>
            </div>
          </div>
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新
          </Button>
        </div>

        {/* 整体健康度 */}
        <Card className="bg-gradient-to-r from-emerald-500 to-teal-600 border-0">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div className="text-white">
                <p className="text-sm opacity-80">系统整体健康度</p>
                <p className="text-5xl font-bold mt-2">{overallHealth.toFixed(1)}%</p>
                <p className="text-sm opacity-80 mt-2">所有核心服务运行正常</p>
              </div>
              <div className="w-32 h-32 rounded-full bg-white/20 flex items-center justify-center">
                <CheckCircle2 className="w-16 h-16 text-white" />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 健康检查项 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {healthChecks.map((check, i) => (
            <Card key={i} className="bg-white/70 backdrop-blur border-slate-200/60">
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-slate-700">{check.name}</p>
                    <p className="text-2xl font-bold text-slate-800 mt-1">{check.value}</p>
                    <p className="text-xs text-slate-500">{check.description}</p>
                  </div>
                  {check.status === "healthy" ? (
                    <CheckCircle2 className="w-8 h-8 text-emerald-500" />
                  ) : (
                    <AlertTriangle className="w-8 h-8 text-amber-500" />
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* 响应时间分布 */}
        <Card className="bg-white/70 backdrop-blur border-slate-200/60">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Clock className="w-4 h-4 text-slate-500" />
              API响应时间分布 (最近30分钟)
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={performanceData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                  <XAxis dataKey="time" tick={{ fontSize: 12 }} stroke="#94a3b8" />
                  <YAxis tick={{ fontSize: 12 }} stroke="#94a3b8" tickFormatter={(v) => `${v}ms`} />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: "white",
                      border: "1px solid #e2e8f0",
                      borderRadius: "8px",
                    }}
                    formatter={(value: number) => [`${value}ms`]}
                  />
                  <Line type="monotone" dataKey="p50" stroke="#10b981" strokeWidth={2} name="P50" />
                  <Line type="monotone" dataKey="p95" stroke="#f59e0b" strokeWidth={2} name="P95" />
                  <Line type="monotone" dataKey="p99" stroke="#ef4444" strokeWidth={2} name="P99" />
                </LineChart>
              </ResponsiveContainer>
            </div>
            <div className="flex items-center justify-center gap-6 mt-4">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-emerald-500" />
                <span className="text-xs text-slate-600">P50: 32ms</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-amber-500" />
                <span className="text-xs text-slate-600">P95: 85ms</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-red-500" />
                <span className="text-xs text-slate-600">P99: 120ms</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 集群节点状态 */}
        <Card className="bg-white/70 backdrop-blur border-slate-200/60">
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Server className="w-4 h-4 text-slate-500" />
              集群节点状态
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-200">
                    <th className="text-left py-3 px-4 text-xs font-medium text-slate-500">节点</th>
                    <th className="text-left py-3 px-4 text-xs font-medium text-slate-500">角色</th>
                    <th className="text-left py-3 px-4 text-xs font-medium text-slate-500">CPU</th>
                    <th className="text-left py-3 px-4 text-xs font-medium text-slate-500">内存</th>
                    <th className="text-left py-3 px-4 text-xs font-medium text-slate-500">状态</th>
                  </tr>
                </thead>
                <tbody>
                  {nodeStatus.map((node) => (
                    <tr key={node.id} className="border-b border-slate-100 hover:bg-slate-50/50">
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <Server className="w-4 h-4 text-slate-400" />
                          <span className="text-sm font-medium text-slate-800">{node.name}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <Badge variant="outline">{node.role}</Badge>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <Progress value={node.cpu} className="w-20 h-2" />
                          <span className="text-sm text-slate-600">{node.cpu}%</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2">
                          <Progress value={node.memory} className="w-20 h-2" />
                          <span className="text-sm text-slate-600">{node.memory}%</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        {node.status === "healthy" ? (
                          <Badge className="bg-emerald-100 text-emerald-700">
                            <CheckCircle2 className="w-3 h-3 mr-1" />
                            正常
                          </Badge>
                        ) : (
                          <Badge className="bg-amber-100 text-amber-700">
                            <AlertTriangle className="w-3 h-3 mr-1" />
                            降级
                          </Badge>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
