import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import {
  Users, Leaf, Radio, Folder, Activity, BarChart3,
  RefreshCw, Wifi, Zap, Clock,
  Cpu, ArrowUpRight, TrendingUp, Server,
  CheckCircle2, AlertTriangle, XCircle, Globe, Database,
  Gauge,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
  getServiceList, getSystemMetrics, getTrafficData,
  type ServiceStatus, type SystemMetrics, type TrafficPoint,
} from '@/api/dashboard'

// ==================== Metric Ring ====================

function MetricRing({ value, max = 100, size = 80, strokeWidth = 7, color, label, suffix = '%' }: {
  value: number; max?: number; size?: number; strokeWidth?: number; color: string; label: string; suffix?: string
}) {
  const r = (size - strokeWidth) / 2
  const c = 2 * Math.PI * r
  const pct = Math.min(value / max, 1)
  const offset = c * (1 - pct)
  const getColor = () => {
    if (color === 'auto') return pct > 0.85 ? '#ef4444' : pct > 0.65 ? '#f59e0b' : '#10b981'
    return color
  }

  return (
    <div className="flex flex-col items-center gap-1.5">
      <div className="relative" style={{ width: size, height: size }}>
        <svg width={size} height={size} className="-rotate-90">
          <circle cx={size / 2} cy={size / 2} r={r} fill="none"
            stroke="currentColor" strokeWidth={strokeWidth}
            className="text-muted/30 dark:text-muted/20" />
          <circle cx={size / 2} cy={size / 2} r={r} fill="none"
            stroke={getColor()} strokeWidth={strokeWidth}
            strokeDasharray={c} strokeDashoffset={offset}
            strokeLinecap="round"
            className="transition-all duration-1000 ease-out" />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <span className="text-sm font-bold tabular-nums">{Math.round(value)}{suffix}</span>
        </div>
      </div>
      <span className="text-[11px] text-muted-foreground font-medium">{label}</span>
    </div>
  )
}

// ==================== Traffic Bar Chart ====================

function TrafficChart({ data }: { data: TrafficPoint[] }) {
  const maxReq = Math.max(...data.map(d => d.requests), 1)

  return (
    <div className="flex items-end gap-[3px] h-32 w-full px-1">
      {data.map((d, i) => {
        const h = (d.requests / maxReq) * 100
        const errH = d.errors > 0 ? Math.max((d.errors / maxReq) * 100, 2) : 0
        return (
          <div key={i} className="flex-1 flex flex-col items-center gap-0.5 group relative">
            {/* Tooltip */}
            <div className="absolute -top-16 left-1/2 -translate-x-1/2 bg-popover text-popover-foreground border border-border shadow-lg rounded-lg px-2.5 py-1.5 text-[10px] whitespace-nowrap opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-10">
              <p className="font-semibold">{d.hour}</p>
              <p className="text-emerald-500">{d.requests} 请求</p>
              {d.errors > 0 && <p className="text-red-500">{d.errors} 错误</p>}
            </div>
            {/* Bar */}
            <div className="w-full rounded-t-sm bg-emerald-500/70 dark:bg-emerald-400/60 group-hover:bg-emerald-500 transition-all duration-300"
              style={{ height: `${h}%`, minHeight: 2, animationDelay: `${i * 30}ms` }} />
            {errH > 0 && (
              <div className="w-full rounded-t-sm bg-red-400/70"
                style={{ height: `${errH}%`, minHeight: 1 }} />
            )}
            {/* X label (every 4h) */}
            {i % 4 === 0 && (
              <span className="text-[9px] text-muted-foreground mt-1 tabular-nums">{d.hour.slice(0, 2)}</span>
            )}
          </div>
        )
      })}
    </div>
  )
}

// ==================== Components ====================

function MetricStatCard({ icon: Icon, title, value, sub, color, dot }: {
  icon: any; title: string; value: string | React.ReactNode; sub: string; color: string; dot?: string
}) {
  return (
    <Card className="border-0 shadow-soft glass-card group cursor-default overflow-hidden relative">
      <div className={`absolute top-0 left-0 w-1 h-full bg-${color}-500/50 group-hover:bg-${color}-500 transition-colors`} />
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
          {dot && <span className={`w-2 h-2 rounded-full ${dot} animate-pulse`} />}
          {title}
        </CardTitle>
        <div className={`p-2 rounded-xl bg-${color}-500/10 text-${color}-500 group-hover:bg-${color}-500 group-hover:text-white transition-colors shadow-sm`}>
          <Icon className="h-4 w-4" />
        </div>
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        <div className="text-xs text-muted-foreground mt-1">{sub}</div>
      </CardContent>
    </Card>
  )
}

// ==================== Status Helpers ====================

const statusConfig = {
  healthy: { label: '正常', icon: CheckCircle2, color: 'text-emerald-500', bg: 'bg-emerald-500/10', dot: 'bg-emerald-500' },
  degraded: { label: '降级', icon: AlertTriangle, color: 'text-amber-500', bg: 'bg-amber-500/10', dot: 'bg-amber-500' },
  down: { label: '离线', icon: XCircle, color: 'text-red-500', bg: 'bg-red-500/10', dot: 'bg-red-500' },
}

const svcIcons: Record<string, React.ReactNode> = {
  'svc-plant': <Leaf className="h-4 w-4" />,
  'svc-radio': <Radio className="h-4 w-4" />,
  'svc-gateway': <Globe className="h-4 w-4" />,
  'svc-db': <Database className="h-4 w-4" />,
  'svc-redis': <Zap className="h-4 w-4" />,
  'svc-etcd': <Server className="h-4 w-4" />,
}

// ==================== Static Data ====================

const activities = [
  { user: '张三', action: '发布了新帖子', target: '我的阳台花园改造', time: '5 分钟前', avatar: '张' },
  { user: '李四', action: '上传了音频', target: '春日晨曲', time: '12 分钟前', avatar: '李' },
  { user: '王五', action: '兑换了商品', target: '精美花盆', time: '30 分钟前', avatar: '王' },
  { user: '赵六', action: '新增了百科', target: '绿萝养护指南', time: '1 小时前', avatar: '赵' },
  { user: 'admin', action: '更新了菜单配置', target: '系统管理', time: '2 小时前', avatar: 'A' },
]

const quickLinks = [
  { title: '用户管理', path: '/system/users', icon: Users, desc: '管理系统用户' },
  { title: '植物百科', path: '/plant/wiki/wiki', icon: Leaf, desc: '管理植物百科' },
  { title: '频道管理', path: '/radio/channel', icon: Radio, desc: '管理电台频道' },
  { title: '文件管理', path: '/system/files', icon: Folder, desc: '管理上传文件' },
]

// ==================== Dashboard ====================

export default function Dashboard() {
  const [services, setServices] = useState<ServiceStatus[]>([])
  const [metrics, setMetrics] = useState<SystemMetrics | null>(null)
  const [traffic, setTraffic] = useState<TrafficPoint[]>([])
  const [loading, setLoading] = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date())

  const fetchAll = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    else setRefreshing(true)
    try {
      const [s, m, t] = await Promise.all([getServiceList(), getSystemMetrics(), getTrafficData()])
      setServices(s); setMetrics(m); setTraffic(t); setLastRefresh(new Date())
    } finally { setLoading(false); setRefreshing(false) }
  }, [])

  useEffect(() => { fetchAll() }, [fetchAll])
  // Auto-refresh every 30s
  useEffect(() => { const id = setInterval(() => fetchAll(true), 30000); return () => clearInterval(id) }, [fetchAll])

  const healthyCount = services.filter(s => s.status === 'healthy').length
  const totalCount = services.length
  const allHealthy = healthyCount === totalCount && totalCount > 0

  return (
    <div className="space-y-6 animate-fadeIn pb-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">仪表盘</h1>
          <p className="text-muted-foreground mt-1">Sundynix 微服务管理控制台 · 系统监控</p>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-xs text-muted-foreground tabular-nums hidden sm:block">
            上次刷新 {lastRefresh.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
          </span>
          <Button variant="outline" size="sm" onClick={() => fetchAll(true)} disabled={refreshing}
            className="gap-1.5 rounded-full h-8 px-3 text-xs">
            <RefreshCw className={`h-3.5 w-3.5 ${refreshing ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        </div>
      </div>

      {loading ? (
        <div className="h-[400px] flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
      ) : (
        <>
          {/* Metric Stats Row */}
          {metrics && (
            <div className="grid gap-4 grid-cols-2 lg:grid-cols-4">
              <MetricStatCard icon={Gauge} title="全局健康" value={allHealthy ? '健康' : '异常'}
                sub={`${healthyCount}/${totalCount} 服务在线`}
                color={allHealthy ? 'emerald' : 'amber'}
                dot={allHealthy ? 'bg-emerald-500' : 'bg-amber-500'} />
              <MetricStatCard icon={Activity} title="24h 请求量"
                value={metrics.totalRequests24h.toLocaleString()} sub={`平均响应 ${metrics.avgResponseTime}ms`}
                color="blue" />
              <MetricStatCard icon={Wifi} title="活跃连接" value={String(metrics.activeConnections)}
                sub={`错误率 ${metrics.errorRate}%`} color="purple" />
              <MetricStatCard icon={Clock} title="连续运行" value={`${metrics.uptimeHours}h`}
                sub={`${(metrics.uptimeHours / 24).toFixed(0)} 天`} color="amber" />
            </div>
          )}

          <div className="grid gap-6 grid-cols-1 lg:grid-cols-3 mt-6">
            {/* Services Grid */}
            <Card className="lg:col-span-2 border-border/60 shadow-soft">
              <CardHeader className="pb-3 border-b border-border/40">
                <CardTitle className="text-lg flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Server className="h-5 w-5 text-primary" /> 核心服务状态
                  </div>
                  <span className="text-xs font-normal text-muted-foreground bg-muted/50 px-2 py-0.5 rounded-full">
                    {healthyCount} / {totalCount} 正常
                  </span>
                </CardTitle>
              </CardHeader>
              <CardContent className="pt-4">
                <div className="grid gap-3 sm:grid-cols-2">
                  {services.map(svc => {
                    const status = statusConfig[svc.status]
                    const Icon = status.icon
                    const SvcIcon = svcIcons[svc.id] || <Server className="h-4 w-4" />
                    return (
                      <div key={svc.id} className="p-3 rounded-xl border border-border/50 hover:border-border/80 transition-colors bg-card flex flex-col gap-3 group">
                        <div className="flex justify-between items-start">
                          <div className="flex items-center gap-2">
                            <div className="p-1.5 rounded-md bg-primary/10 text-primary">
                              {SvcIcon}
                            </div>
                            <div>
                              <div className="text-sm font-semibold">{svc.name}</div>
                              <div className="text-[10px] text-muted-foreground font-mono">{svc.endpoint}</div>
                            </div>
                          </div>
                          <div className={`flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full ${status.bg} ${status.color}`}>
                            <Icon className="h-3 w-3" />
                            {status.label}
                          </div>
                        </div>

                        <div className="grid grid-cols-3 gap-2 pt-2 border-t border-border/40">
                          <div className="flex flex-col">
                            <span className="text-[10px] text-muted-foreground">延迟</span>
                            <span className="text-xs font-medium tabular-nums">{svc.latency}ms</span>
                          </div>
                          <div className="flex flex-col">
                            <span className="text-[10px] text-muted-foreground">CPU</span>
                            <div className="flex items-center gap-1">
                              <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                                <div className={`h-full rounded-full transition-all duration-1000 ${svc.cpu > 80 ? 'bg-red-500' : svc.cpu > 50 ? 'bg-amber-500' : 'bg-emerald-500'}`} style={{ width: `${svc.cpu}%` }} />
                              </div>
                              <span className="text-[10px] tabular-nums font-medium min-w-[2ch]">{svc.cpu}%</span>
                            </div>
                          </div>
                          <div className="flex flex-col">
                            <span className="text-[10px] text-muted-foreground">RAM</span>
                            <div className="flex items-center gap-1">
                              <div className="flex-1 h-1.5 bg-muted rounded-full overflow-hidden">
                                <div className={`h-full rounded-full transition-all duration-1000 ${svc.memory > 85 ? 'bg-red-500' : svc.memory > 60 ? 'bg-amber-500' : 'bg-blue-500'}`} style={{ width: `${svc.memory}%` }} />
                              </div>
                              <span className="text-[10px] tabular-nums font-medium min-w-[2ch]">{svc.memory}%</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    )
                  })}
                </div>
              </CardContent>
            </Card>

            {/* System Resources & Traffic */}
            <div className="space-y-6">
              <Card className="border-border/60 shadow-soft">
                <CardHeader className="pb-2">
                  <CardTitle className="text-lg flex items-center gap-2">
                    <Cpu className="h-5 w-5 text-primary" /> 资源使用率
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-2">
                  <div className="flex justify-between items-center px-2">
                    <MetricRing value={metrics?.cpuUsage || 0} color="auto" label="CPU使用率" />
                    <MetricRing value={metrics?.memoryUsage || 0} color="auto" label="内存使用率" />
                    <MetricRing value={metrics?.diskUsage || 0} color="#3b82f6" label="磁盘空间" />
                  </div>
                </CardContent>
              </Card>

              <Card className="border-border/60 shadow-soft flex-1">
                <CardHeader className="pb-2">
                  <CardTitle className="text-lg flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <BarChart3 className="h-5 w-5 text-primary" /> 请求趋势
                    </div>
                    <span className="text-[10px] text-muted-foreground">过去24小时</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-4 pb-2">
                  <TrafficChart data={traffic} />
                </CardContent>
              </Card>
            </div>
          </div>

          {/* Quick Links + Activity */}
          <div className="grid gap-6 lg:grid-cols-5 mt-6">
            {/* Quick Links */}
            <Card className="lg:col-span-2 border-border/60 shadow-soft">
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <ArrowUpRight className="h-5 w-5 text-primary" /> 快捷入口
                </CardTitle>
                <CardDescription>常用管理页面快速访问</CardDescription>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-3">
                {quickLinks.map(l => (
                  <Link key={l.path} to={l.path}
                    className="flex flex-col gap-2 p-4 rounded-xl border border-border/50 hover:border-primary/30 hover:bg-primary/5 transition-all group">
                    <l.icon className="h-5 w-5 text-muted-foreground group-hover:text-primary transition-colors" />
                    <div>
                      <p className="text-sm font-medium">{l.title}</p>
                      <p className="text-xs text-muted-foreground">{l.desc}</p>
                    </div>
                  </Link>
                ))}
              </CardContent>
            </Card>

            {/* Recent Activity */}
            <Card className="lg:col-span-3 border-border/60 shadow-soft">
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <TrendingUp className="h-5 w-5 text-primary" /> 最近动态
                </CardTitle>
                <CardDescription>系统最新操作记录</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {activities.map((a, i) => (
                    <div key={i} className="flex items-center gap-4 group">
                      <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary text-sm font-bold">
                        {a.avatar}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm">
                          <span className="font-medium">{a.user}</span>
                          <span className="text-muted-foreground"> {a.action} </span>
                          <span className="font-medium text-primary">{a.target}</span>
                        </p>
                        <p className="text-xs text-muted-foreground mt-0.5">{a.time}</p>
                      </div>
                      <span className="text-[10px] text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer">
                        查看详情
                      </span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </>
      )}
    </div>
  )
}
