"use client"
import { useState, useEffect } from "react"
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Progress } from "@/components/ui/progress"
import { FolderOpen, CheckCircle2, AlertCircle, Loader2, Cpu, HardDrive, Zap, XCircle } from "lucide-react"
import { loadModel, getModelStatus, unloadModel, validatePath } from "@/lib/api"

export function ModelLoader({ onLoaded }: { onLoaded?: ()=>void }) {
  const [path, setPath] = useState("C:\\models\\mistral-7b")
  const [dtype, setDtype] = useState("float16")
  const [quant, setQuant] = useState("none")
  const [deviceMap, setDeviceMap] = useState("auto")
  const [loading, setLoading] = useState(false)
  const [status, setStatus] = useState<any>(null)
  const [validation, setValidation] = useState<any>(null)
  const [error, setError] = useState<string|null>(null)

  const fetchStatus = async () => {
    try { const s = await getModelStatus(); setStatus(s) } catch {}
  }
  useEffect(()=>{ fetchStatus(); const id=setInterval(fetchStatus, 3000); return ()=>clearInterval(id)},[])

  const handleValidate = async () => {
    try { const v = await validatePath(path); setValidation(v); setError(null) } catch(e:any){ setError(e.message); setValidation(null) }
  }
  const handleLoad = async () => {
    setLoading(true); setError(null)
    try {
      const res = await loadModel({ model_path: path, dtype, quantization: quant, device_map: deviceMap })
      setStatus(res); onLoaded?.()
    } catch(e:any){ setError(e.message || String(e)) }
    finally{ setLoading(false) }
  }
  const handleUnload = async () => { try{ const s=await unloadModel(); setStatus(s)}catch(e:any){setError(e.message)} }

  const isLoaded = status?.status==="loaded"
  const isLoading = status?.status==="loading" || loading

  return (
    <Card className="border-2">
      <CardHeader>
        <CardTitle className="flex items-center gap-2"><FolderOpen className="h-5 w-5 text-violet-600"/> محرك تحميل أوزان Safetensors</CardTitle>
        <CardDescription>حدد مسار مجلد النموذج الذي يحتوي على ملفات .safetensors و config.json و tokenizer.json</CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        {/* Path input */}
        <div className="space-y-2">
          <label className="text-sm font-medium">مسار مجلد النموذج</label>
          <div className="flex gap-2">
            <Input value={path} onChange={e=>setPath(e.target.value)} placeholder="C:\models\my-model أو /home/user/models/llama" className="flex-1 font-mono text-sm"/>
            <Button variant="outline" onClick={handleValidate}>فحص</Button>
          </div>
          {validation && (
            <div className={`rounded-lg border p-3 text-sm ${validation.valid ? "bg-emerald-50 border-emerald-200 dark:bg-emerald-950/30" : "bg-amber-50 border-amber-200 dark:bg-amber-950/30"}`}>
              <div className="flex items-center gap-2 font-medium">{validation.valid ? <CheckCircle2 className="h-4 w-4 text-emerald-600"/> : <AlertCircle className="h-4 w-4 text-amber-600"/>} {validation.reason}</div>
              {validation.details && <div className="mt-2 text-xs text-zinc-600 dark:text-zinc-400 space-y-1">
                <div>عدد ملفات safetensors: {validation.details.safetensors_count} • الحجم: {validation.details.total_size_mb} MB</div>
                <div className="flex flex-wrap gap-1">{validation.details.safetensors_files?.map((f:string)=><Badge key={f} variant="secondary" className="text-[10px]">{f}</Badge>)}</div>
                <div>config.json: {validation.details.has_config?"✅":"❌"} • tokenizer: {validation.details.has_tokenizer?"✅":"❌"}</div>
              </div>}
            </div>
          )}
        </div>

        {/* Options */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="space-y-1.5">
            <label className="text-sm font-medium">الدقة (Dtype)</label>
            <Select value={dtype} onValueChange={setDtype}>
              <SelectTrigger><SelectValue placeholder="float16"/></SelectTrigger>
              <SelectContent>
                <SelectItem value="float16">Float16 (موصى به)</SelectItem>
                <SelectItem value="bfloat16">Bfloat16</SelectItem>
                <SelectItem value="float32">Float32 (دقة كاملة)</SelectItem>
                <SelectItem value="auto">Auto</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-zinc-500">Float16 يوفر 50% VRAM</p>
          </div>
          <div className="space-y-1.5">
            <label className="text-sm font-medium">التكميم (Quantization)</label>
            <Select value={quant} onValueChange={setQuant}>
              <SelectTrigger><SelectValue placeholder="none"/></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">بدون (None)</SelectItem>
                <SelectItem value="8bit">8-bit (bitsandbytes)</SelectItem>
                <SelectItem value="4bit">4-bit (NF4 - أقل VRAM)</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-zinc-500">{quant==="4bit" ? "يوفر ~75% VRAM" : quant==="8bit" ? "يوفر ~50% VRAM" : "أقصى دقة"}</p>
          </div>
          <div className="space-y-1.5">
            <label className="text-sm font-medium">توزيع الطبقات</label>
            <Select value={deviceMap} onValueChange={setDeviceMap}>
              <SelectTrigger><SelectValue placeholder="auto"/></SelectTrigger>
              <SelectContent>
                <SelectItem value="auto">Auto (تلقائي)</SelectItem>
                <SelectItem value="balanced">Balanced (GPU+RAM)</SelectItem>
                <SelectItem value="sequential">Sequential</SelectItem>
                <SelectItem value="cpu">CPU فقط</SelectItem>
                <SelectItem value="cuda:0">GPU فقط</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-zinc-500">للأجهزة ضعيفة VRAM استخدم Balanced</p>
          </div>
        </div>

        {error && <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-800 dark:bg-red-950/30 dark:text-red-300 flex gap-2"><XCircle className="h-4 w-4 mt-0.5 flex-shrink-0"/>{error}</div>}

        {/* Actions */}
        <div className="flex gap-3">
          <Button onClick={handleLoad} disabled={isLoading} className="flex-1 bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700">
            {isLoading ? <><Loader2 className="h-4 w-4 animate-spin me-2"/> جاري التحميل...</> : <><Zap className="h-4 w-4 me-2"/> تحميل النموذج</>}
          </Button>
          {isLoaded && <Button variant="outline" onClick={handleUnload}>إلغاء التحميل</Button>}
        </div>

        {/* Status */}
        {status && (
          <div className="rounded-xl border bg-zinc-50 dark:bg-zinc-900 p-4 space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">حالة النموذج</span>
              <Badge variant={isLoaded ? "success" : status.status==="error" ? "destructive" : "secondary"}>{status.status==="loaded" ? "محمل" : status.status==="loading" ? "جاري التحميل" : status.status==="error" ? "خطأ" : "غير محمل"}</Badge>
            </div>
            {isLoaded && (
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                <div className="bg-white dark:bg-zinc-800 rounded-lg p-3 border dark:border-zinc-700"><div className="text-xs text-zinc-500 flex items-center gap-1"><HardDrive className="h-3 w-3"/> النوع</div><div className="font-medium">{status.model_type || "unknown"}</div></div>
                <div className="bg-white dark:bg-zinc-800 rounded-lg p-3 border dark:border-zinc-700"><div className="text-xs text-zinc-500 flex items-center gap-1"><Cpu className="h-3 w-3"/> المعاملات</div><div className="font-medium">{status.num_parameters || "-"}</div></div>
                <div className="bg-white dark:bg-zinc-800 rounded-lg p-3 border dark:border-zinc-700"><div className="text-xs text-zinc-500">VRAM المستخدم</div><div className="font-medium">{status.vram_allocated_mb ? `${status.vram_allocated_mb} MB` : "-"}</div></div>
                <div className="bg-white dark:bg-zinc-800 rounded-lg p-3 border dark:border-zinc-700"><div className="text-xs text-zinc-500">زمن التحميل</div><div className="font-medium">{status.load_time_sec ? `${status.load_time_sec}s` : "-"}</div></div>
              </div>
            )}
            {status.error && <div className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded p-2 dark:bg-amber-950/30">{status.error}</div>}
            {status.safetensors_files?.length>0 && <div className="text-xs text-zinc-500">الملفات: {status.safetensors_files.join(", ")}</div>}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
