"use client"
import { useState, useEffect } from "react"
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { getBenchmarkSuites, getBenchmarkResults, createShare, runBenchmarkStream } from "@/lib/api"
import { API_BASE } from "@/lib/utils"
import { FlaskConical, Play, Loader2, CheckCircle2, XCircle, BarChart3, Download, Award, Clock, Zap, HardDrive, Share2, Link2, Copy, FolderOpen } from "lucide-react"
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"
import { CustomDatasetPanel } from "./CustomDatasetPanel"
import { ModelPathSelector } from "./ModelPathSelector"
import { Progress } from "./ui/progress"

export function BenchmarkPanel() {
  const [suites, setSuites] = useState<any>(null)
  const [selected, setSelected] = useState<string[]>(["all"])
  const [judge, setJudge] = useState("regex")
  const [running, setRunning] = useState(false)
  const [report, setReport] = useState<any>(null)
  const [history, setHistory] = useState<any[]>([])
  const [error, setError] = useState<string|null>(null)
  const [shareUrl, setShareUrl] = useState<string|null>(null)
  const [copied, setCopied] = useState(false)
  // progress modal
  const [progress, setProgress] = useState<any>(null)
  const [logs, setLogs] = useState<any[]>([])
  const [elapsed, setElapsed] = useState(0)

  const fetchAll = async ()=>{
    try{ setSuites(await getBenchmarkSuites()); const h = await getBenchmarkResults(); setHistory(h)}catch{}
  }
  useEffect(()=>{fetchAll()},[])
  useEffect(()=>{
    const params = new URLSearchParams(window.location.search)
    const rid = params.get("report")
    if (rid && history.length) {
      const found = history.find((h:any)=>h.id===rid)
      if (found) setReport(found)
    }
  }, [history])

  // timer for progress
  useEffect(()=>{
    if (!running) return
    const t0 = Date.now()
    const id = setInterval(()=>setElapsed(Math.floor((Date.now()-t0)/1000)), 1000)
    return ()=>clearInterval(id)
  }, [running])

  const toggleSuite = (s:string)=>{
    if (s==="all") setSelected(["all"])
    else {
      let next = selected.includes("all") ? [s] : selected.includes(s) ? selected.filter(x=>x!==s) : [...selected, s]
      if (next.length===0) next=["all"]
      setSelected(next)
    }
  }

  const handleRun = async ()=>{
    setRunning(true); setError(null); setReport(null); setShareUrl(null); setProgress({current:0,total: selected.includes("all")?15: selected.length*4, name:"تهيئة...", percent:0}); setLogs([]); setElapsed(0)
    try{
      await runBenchmarkStream({ suites: selected, judge_mode: judge, temperature: 0.2 }, (ev:any)=>{
        if (ev.type==="start") {
          setProgress({current:0,total:ev.total, name:"بدء الاختبار...", percent:0})
        } else if (ev.type==="progress") {
          setProgress(ev)
        } else if (ev.type==="task_done") {
          setLogs(prev=>[...prev, ev])
          setProgress((p:any)=>({...p, current: ev.current, percent: Math.round(ev.current/ev.total*100)}))
        } else if (ev.type==="done") {
          // report is inside
          const r = ev.report
          // ensure timestamp is string already
          setReport(r)
          fetchAll()
        }
      })
    } catch(e:any){ setError(e.message)}
    finally{ setRunning(false); setTimeout(()=>setProgress(null), 800)}
  }

  const handleShare = async ()=>{
    if (!report) return
    try{
      const res = await createShare(report.id)
      const url = `${window.location.origin}/share/${res.token}`
      setShareUrl(url)
      await navigator.clipboard.writeText(url)
      setCopied(true)
      setTimeout(()=>setCopied(false), 2000)
    } catch(e:any){ setError(e.message)}
  }

  const exportHref = (fmt:string, id:string)=> `${API_BASE}/api/export/${fmt}?report_id=${id}`

  return (
    <div className="space-y-6">
      {/* Model path selector - NEW */}
      <ModelPathSelector compact onLoaded={fetchAll} />

      <Tabs defaultValue="preset" className="w-full">
        <TabsList>
          <TabsTrigger value="preset">الاختبارات الجاهزة</TabsTrigger>
          <TabsTrigger value="custom">بياناتك المخصصة 🌐</TabsTrigger>
        </TabsList>
        <TabsContent value="preset">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2"><FlaskConical className="h-5 w-5 text-violet-600"/> نظام الاختبار المبرمج</CardTitle>
              <CardDescription>اختر حزم الاختبار وطريقة التقييم ثم شغّل — حدد مسار النموذج أعلاه قبل التشغيل</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <label className="text-sm font-medium">حزم الاختبار</label>
                <div className="flex flex-wrap gap-2 mt-2">
                  {[
                    {id:"all", label:"الكل (15 اختبار)"},
                    {id:"reasoning", label:"Reasoning (4)"},
                    {id:"coding", label:"Coding (4)"},
                    {id:"arabic", label:"Arabic Quality (4)"},
                    {id:"summarization", label:"Summarization (3)"},
                  ].map(s=>(
                    <button key={s.id} onClick={()=>toggleSuite(s.id)} className={`px-4 py-2 rounded-full text-sm border transition-colors ${selected.includes(s.id)?"bg-zinc-900 text-white border-zinc-900":"bg-white hover:bg-zinc-50 dark:bg-zinc-900"}`}>{s.label}</button>
                  ))}
                </div>
              </div>
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium">طريقة التقييم</label>
                  <div className="flex gap-2 mt-2">
                    {[
                      {id:"regex", label:"Regex"},
                      {id:"exact", label:"Exact Match"},
                      {id:"llm", label:"LLM-as-Judge"},
                    ].map(m=> <button key={m.id} onClick={()=>setJudge(m.id)} className={`flex-1 py-2 rounded-lg text-sm border ${judge===m.id?"bg-violet-600 text-white border-violet-600":"bg-white hover:bg-zinc-50"}`}>{m.label}</button>)}
                  </div>
                </div>
                <div className="flex items-end">
                  <Button onClick={handleRun} disabled={running} className="w-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11">
                    {running ? <><Loader2 className="h-4 w-4 animate-spin me-2"/> جاري التشغيل...</> : <><Play className="h-4 w-4 me-2"/> تشغيل الاختبارات</>}
                  </Button>
                </div>
              </div>
              {error && <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">{error} — تأكد من تحميل النموذج أعلاه (المسار C:\Users\RDP\Desktop\model).</div>}
              {suites && (
                <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-3 pt-2">
                  {Object.entries(suites).map(([k,tasks]:any)=>(
                    <div key={k} className="rounded-lg border p-3 bg-zinc-50 dark:bg-zinc-900">
                      <div className="text-xs font-bold uppercase tracking-wide text-violet-700">{k}</div>
                      <div className="mt-1 space-y-1">{tasks.slice(0,3).map((t:any)=><div key={t.id} className="text-xs text-zinc-600 truncate">• {t.name}</div>)}<div className="text-xs text-zinc-400">+{tasks.length} اختبارات</div></div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
        <TabsContent value="custom">
          <CustomDatasetPanel onReport={(r)=>{ setReport(r); fetchAll() }} />
        </TabsContent>
      </Tabs>

      {/* Progress Modal - NEW */}
      {running && progress && (
        <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4">
          <Card className="w-full max-w-2xl max-h-[85vh] flex flex-col">
            <CardHeader className="pb-3">
              <CardTitle className="flex items-center gap-2 text-base"><Loader2 className="h-5 w-5 animate-spin text-violet-600"/> جاري اختبار النموذج...</CardTitle>
              <CardDescription>النموذج يولّد الإجابات واحداً تلو الآخر — لا تغلق الصفحة • {elapsed}s</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4 overflow-y-auto">
              <div className="space-y-2">
                <div className="flex justify-between text-sm"><span className="font-medium">{progress.name || "تهيئة..."}</span><span className="text-zinc-500">{progress.current || 0}/{progress.total || 15}</span></div>
                <Progress value={progress.percent || (progress.current/progress.total*100) || 0} />
                <div className="text-xs text-zinc-500 truncate">الـ Prompt: {progress.prompt || "..."}</div>
                <div className="flex gap-2 text-xs">
                  <span className="px-2 py-1 rounded-full bg-violet-50 border border-violet-200">{progress.category || "-"}</span>
                  <span className="px-2 py-1 rounded-full bg-zinc-100 border">{progress.percent || 0}%</span>
                </div>
              </div>
              <div className="rounded-xl border bg-zinc-50 dark:bg-zinc-900 p-3">
                <div className="text-xs font-medium mb-2 flex items-center gap-2"><FolderOpen className="h-3 w-3"/> سجل المهام المكتملة ({logs.length})</div>
                <div className="space-y-1 max-h-48 overflow-y-auto">
                  {logs.length===0 ? <div className="text-xs text-zinc-400">بانتظار أول مهمة...</div> : logs.map((l:any,i:number)=>(
                    <div key={i} className="flex items-center justify-between p-2 bg-white dark:bg-zinc-800 rounded border text-xs">
                      <span className="truncate flex-1">{l.current}. {l.name}</span>
                      <span className={`ms-2 px-2 py-0.5 rounded-full text-[10px] border ${l.passed?"bg-emerald-50 border-emerald-200 text-emerald-700":"bg-red-50 border-red-200 text-red-700"}`}>{l.passed?"✓":"✗"} {l.tps} t/s</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="text-xs text-zinc-500 text-center">السرعة الحالية ~2 t/s على CPU — 15 مهمة مقيدة 32 token ≈ 2-3 دقائق إجمالاً. شاشة التقرير ستظهر تلقائياً عند الانتهاء.</div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Current Report */}
      {report && (
        <Card className="border-violet-200 dark:border-violet-900">
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center gap-2"><Award className="h-5 w-5 text-amber-500"/> نتائج الاختبار - {report.id}</span>
              <Badge variant={report.accuracy>=0.7?"success": report.accuracy>=0.4?"warning":"destructive"}>{(report.accuracy*100).toFixed(1)}% دقة</Badge>
            </CardTitle>
            <CardDescription>{report.model_path} • {new Date(report.timestamp).toLocaleString("ar-EG")} • {report.passed}/{report.total_tasks} ناجح</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
              <div className="rounded-xl bg-gradient-to-br from-violet-600 to-indigo-600 text-white p-4"><div className="text-xs opacity-80">الدقة</div><div className="text-2xl font-bold">{(report.accuracy*100).toFixed(1)}%</div><div className="text-xs opacity-80">{report.passed}/{report.total_tasks}</div></div>
              <div className="rounded-xl border p-4"><div className="text-xs text-zinc-500 flex items-center gap-1"><Zap className="h-3 w-3"/> متوسط السرعة</div><div className="text-xl font-bold">{report.avg_tokens_per_sec} t/s</div><div className="text-xs text-zinc-500">TTFT {report.avg_ttft_ms}ms</div></div>
              <div className="rounded-xl border p-4"><div className="text-xs text-zinc-500 flex items-center gap-1"><Clock className="h-3 w-3"/> متوسط الزمن</div><div className="text-xl font-bold">{report.avg_latency_ms}ms</div><div className="text-xs text-zinc-500">لكل مهمة</div></div>
              <div className="rounded-xl border p-4"><div className="text-xs text-zinc-500 flex items-center gap-1"><HardDrive className="h-3 w-3"/> ذروة VRAM</div><div className="text-xl font-bold">{report.vram_peak_mb} MB</div><div className="text-xs text-zinc-500">{report.vram_peak_mb>8000?"مستهلك عالي":"كفاءة جيدة"}</div></div>
            </div>

            <div className="grid lg:grid-cols-2 gap-4">
              <div className="h-[240px] border rounded-xl p-3">
                <div className="text-sm font-medium mb-2">الدقة حسب الفئة</div>
                <ResponsiveContainer width="100%" height="90%">
                  <BarChart data={Object.entries(report.by_category).map(([k,v]:any)=>({name:k, acc: v.accuracy*100, tps: v.avg_tps}))}>
                    <CartesianGrid strokeDasharray="3 3"/>
                    <XAxis dataKey="name" tick={{fontSize:10}}/>
                    <YAxis tick={{fontSize:10}} domain={[0,100]}/>
                    <Tooltip/>
                    <Bar dataKey="acc" fill="#7c3aed" name="Accuracy %" radius={[6,6,0,0]}/>
                  </BarChart>
                </ResponsiveContainer>
              </div>
              <div className="h-[240px] border rounded-xl p-3">
                <div className="text-sm font-medium mb-2">السرعة (Tokens/sec) حسب الفئة</div>
                <ResponsiveContainer width="100%" height="90%">
                  <BarChart data={Object.entries(report.by_category).map(([k,v]:any)=>({name:k, tps: v.avg_tps}))}>
                    <CartesianGrid strokeDasharray="3 3"/>
                    <XAxis dataKey="name" tick={{fontSize:10}}/>
                    <YAxis tick={{fontSize:10}}/>
                    <Tooltip/>
                    <Bar dataKey="tps" fill="#10b981" name="TPS" radius={[6,6,0,0]}/>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            <div className="rounded-xl bg-zinc-50 dark:bg-zinc-900 border p-4">
              <div className="font-medium text-sm flex items-center gap-2"><BarChart3 className="h-4 w-4"/> التحليل والاستنتاجات</div>
              <div className="mt-2 grid md:grid-cols-2 gap-3 text-sm">
                {report.by_category && (()=>{ const best = Object.entries(report.by_category).sort((a:any,b:any)=>b[1].accuracy-a[1].accuracy)[0]; const worst = Object.entries(report.by_category).sort((a:any,b:any)=>a[1].accuracy-b[1].accuracy)[0]; return <>
                  <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-3 dark:bg-emerald-950/30"><div className="font-medium text-emerald-700">💪 نقطة قوة: {best?.[0]}</div><div className="text-xs text-zinc-600">دقة {(best?.[1] as any).accuracy*100}% • سرعة {(best?.[1] as any).avg_tps} t/s</div></div>
                  <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 dark:bg-amber-950/30"><div className="font-medium text-amber-700">⚠️ نقطة ضعف: {worst?.[0]}</div><div className="text-xs text-zinc-600">دقة {(worst?.[1] as any).accuracy*100}% • يحتاج تحسين</div></div>
                </> })()}
              </div>
              <div className="mt-3 text-xs text-zinc-500">VRAM الذروة {report.vram_peak_mb} MB — {report.vram_peak_mb>8000 ? "يُنصح باستخدام 4-bit quantization" : "استهلاك معتدل"}</div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b text-xs text-zinc-500"><th className="text-start py-2 px-2">المهمة</th><th>الفئة</th><th>النتيجة</th><th>TPS</th><th>TTFT</th><th>VRAM</th></tr></thead>
                <tbody>{report.results.map((r:any)=>(
                  <tr key={r.task_id} className="border-b hover:bg-zinc-50 dark:hover:bg-zinc-900">
                    <td className="py-2 px-2"><div className="font-medium">{r.name}</div><div className="text-xs text-zinc-500 truncate max-w-[260px]">{r.prompt.slice(0,80)}</div></td>
                    <td className="text-center"><Badge variant="secondary" className="text-xs">{r.category}</Badge></td>
                    <td className="text-center">{r.passed ? <CheckCircle2 className="h-4 w-4 text-emerald-600 mx-auto"/> : <XCircle className="h-4 w-4 text-red-500 mx-auto"/>}</td>
                    <td className="text-center">{r.tokens_per_sec}</td>
                    <td className="text-center">{r.ttft_ms}</td>
                    <td className="text-center">{r.vram_peak_mb}</td>
                  </tr>
                ))}</tbody>
              </table>
            </div>

            <div className="flex flex-wrap gap-2 items-center">
              <a href={exportHref("json", report.id)} download className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-zinc-900 text-white text-sm hover:bg-zinc-800"><Download className="h-4 w-4"/> JSON</a>
              <a href={exportHref("csv", report.id)} download className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border text-sm hover:bg-zinc-50"><Download className="h-4 w-4"/> CSV</a>
              <a href={exportHref("pdf", report.id)} download className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border text-sm hover:bg-zinc-50"><Download className="h-4 w-4"/> PDF (عربي)</a>
              <Button variant="outline" onClick={handleShare} className="gap-2"><Share2 className="h-4 w-4"/> مشاركة التقرير</Button>
              {shareUrl && <span className="text-xs bg-emerald-50 border border-emerald-200 px-3 py-2 rounded-lg flex items-center gap-2"><Link2 className="h-3 w-3"/> {shareUrl} <button onClick={()=>navigator.clipboard.writeText(shareUrl)} className="ms-2 p-1 hover:bg-white rounded"><Copy className="h-3 w-3"/></button> {copied && <span className="text-emerald-700">تم النسخ!</span>}</span>}
            </div>
            {shareUrl && <div className="text-xs text-zinc-500">يمكن لأي شخص فتح الرابط ومشاهدة التقرير — يعتمد على الرمز المميز token ولا يحتاج تسجيل.</div>}
          </CardContent>
        </Card>
      )}

      {history.length>0 && (
        <Card>
          <CardHeader><CardTitle className="text-sm">سجل التقارير السابق</CardTitle></CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b text-xs text-zinc-500"><th className="text-start py-2">ID</th><th>التاريخ</th><th>النموذج</th><th>الدقة</th><th>TPS</th><th>الإجراءات</th></tr></thead>
                <tbody>{history.slice(0,10).map((h:any)=>(
                  <tr key={h.id} className="border-b hover:bg-zinc-50">
                    <td className="py-2 font-mono text-xs">{h.id}</td>
                    <td className="text-xs">{new Date(h.timestamp).toLocaleString("ar-EG")}</td>
                    <td className="text-xs truncate max-w-[180px]">{h.model_path}</td>
                    <td><Badge variant={h.accuracy>=0.7?"success": h.accuracy>=0.4?"warning":"destructive"}>{(h.accuracy*100).toFixed(0)}%</Badge></td>
                    <td className="text-xs">{h.avg_tokens_per_sec}</td>
                    <td className="flex gap-1 py-1">
                      <Button size="sm" variant="outline" className="h-7 text-xs" onClick={()=>setReport(h)}>عرض</Button>
                      <a href={exportHref("json", h.id)} className="text-xs px-2 py-1 border rounded hover:bg-zinc-50">JSON</a>
                      <a href={exportHref("pdf", h.id)} className="text-xs px-2 py-1 border rounded hover:bg-zinc-50">PDF</a>
                    </td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
