"use client"
import { useEffect, useState } from "react"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { getTelemetry, getHistory } from "@/lib/api"
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, BarChart, Bar } from "recharts"
import { Activity, Cpu, HardDrive, Thermometer, Zap } from "lucide-react"

export function TelemetryCharts() {
  const [snap, setSnap] = useState<any>(null)
  const [history, setHistory] = useState<any[]>([])
  const [tpsHistory, setTpsHistory] = useState<any[]>([])

  useEffect(()=>{
    const fetchSnap = async ()=>{
      try{
        const s = await getTelemetry()
        setSnap(s)
        setHistory(prev=>{
          const next = [...prev, { time: new Date(s.timestamp).toLocaleTimeString("ar-EG"), vram: s.vram_used_mb, vram_percent: s.vram_percent, cpu: s.cpu_percent, ram: s.ram_percent }]
          return next.slice(-30)
        })
        if (s.tokens_per_sec) {
          setTpsHistory(prev=>{
            const next = [...prev, { time: new Date(s.timestamp).toLocaleTimeString("ar-EG"), tps: s.tokens_per_sec }]
            return next.slice(-30)
          })
        }
      } catch{}
    }
    fetchSnap()
    const id = setInterval(fetchSnap, 1200)
    // try load history
    getHistory(30).then((h:any)=>{
      if (Array.isArray(h) && h.length) {
        setHistory(h.map((s:any)=>({ time: new Date(s.timestamp).toLocaleTimeString("ar-EG"), vram: s.vram_used_mb, vram_percent: s.vram_percent, cpu: s.cpu_percent, ram: s.ram_percent })))
      }
    }).catch(()=>{})
    return ()=>clearInterval(id)
  },[])

  // WebSocket disabled - using HTTP polling only to avoid 404/hammering during benchmark
  // Polling above (1200ms) is sufficient and more stable on CPU

  if (!snap) return <Card><CardContent className="p-6">جاري تحميل بيانات العتاد...</CardContent></Card>

  return (
    <div className="space-y-4">
      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between"><span className="text-xs text-zinc-500 flex items-center gap-1"><HardDrive className="h-3 w-3"/> VRAM</span><Badge variant={snap.vram_percent>85?"destructive": snap.vram_percent>60?"warning":"secondary"}>{snap.vram_percent}%</Badge></div>
            <div className="text-lg font-bold mt-1">{snap.vram_used_mb?.toFixed(0)} / {snap.vram_total_mb?.toFixed(0)} MB</div>
            <Progress value={snap.vram_percent} className="mt-2" indicatorClassName={snap.vram_percent>85?"bg-red-500": snap.vram_percent>60?"bg-amber-500":"bg-violet-600"}/>
            <div className="text-xs text-zinc-500 mt-1">الذروة: {snap.vram_peak_mb?.toFixed(0)} MB • {snap.gpu_name}</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between"><span className="text-xs text-zinc-500 flex items-center gap-1"><Activity className="h-3 w-3"/> GPU Util</span><Badge variant="outline">{snap.gpu_util_percent}%</Badge></div>
            <div className="text-lg font-bold mt-1">{snap.gpu_util_percent}%</div>
            <Progress value={snap.gpu_util_percent} className="mt-2"/>
            <div className="text-xs text-zinc-500 mt-1 flex items-center gap-2"><Thermometer className="h-3 w-3"/> {snap.gpu_temp_c || "-"}°C • <Zap className="h-3 w-3"/> {snap.gpu_power_w||"-"}W</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between"><span className="text-xs text-zinc-500 flex items-center gap-1"><Cpu className="h-3 w-3"/> CPU</span><Badge variant="secondary">{snap.cpu_percent}%</Badge></div>
            <div className="text-lg font-bold mt-1">{snap.cpu_percent}%</div>
            <Progress value={snap.cpu_percent} className="mt-2" indicatorClassName="bg-emerald-600"/>
            <div className="text-xs text-zinc-500 mt-1">RAM: {snap.ram_used_mb?.toFixed(0)} / {snap.ram_total_mb?.toFixed(0)} MB ({snap.ram_percent}%)</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="text-xs text-zinc-500">Tokens / sec (حالي)</div>
            <div className="text-lg font-bold mt-1">{snap.tokens_per_sec ? `${snap.tokens_per_sec.toFixed(1)} t/s` : "—"}</div>
            <div className="text-xs text-zinc-500 mt-2">{snap.has_gpu ? "GPU فعال" : "وضع CPU / محاكاة"}</div>
            <div className={`mt-2 h-2 rounded-full ${snap.has_gpu?"bg-emerald-500":"bg-amber-500"}`}></div>
          </CardContent>
        </Card>
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm">استهلاك VRAM عبر الزمن (آخر 30 نقطة)</CardTitle></CardHeader>
          <CardContent className="h-[240px]">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={history}>
                <CartesianGrid strokeDasharray="3 3" stroke="#eee"/>
                <XAxis dataKey="time" tick={{fontSize:10}} interval={4}/>
                <YAxis tick={{fontSize:10}} unit=" MB"/>
                <Tooltip />
                <Area type="monotone" dataKey="vram" stroke="#7c3aed" fill="#ede9fe" strokeWidth={2} name="VRAM MB"/>
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm">CPU و RAM % مقابل VRAM %</CardTitle></CardHeader>
          <CardContent className="h-[240px]">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={history}>
                <CartesianGrid strokeDasharray="3 3" stroke="#eee"/>
                <XAxis dataKey="time" tick={{fontSize:10}} interval={4}/>
                <YAxis tick={{fontSize:10}} unit="%" domain={[0,100]}/>
                <Tooltip />
                <Line type="monotone" dataKey="cpu" stroke="#10b981" strokeWidth={2} dot={false} name="CPU %"/>
                <Line type="monotone" dataKey="ram" stroke="#f59e0b" strokeWidth={2} dot={false} name="RAM %"/>
                <Line type="monotone" dataKey="vram_percent" stroke="#7c3aed" strokeWidth={2} dot={false} name="VRAM %"/>
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
