"use client"
import { useEffect, useState } from "react"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { getModelStatus, validatePath, loadModel } from "@/lib/api"
import { FolderOpen, CheckCircle2, AlertCircle, Loader2, Cpu, HardDrive } from "lucide-react"
import Link from "next/link"

export function ModelPathSelector({ compact=false, onLoaded }: { compact?: boolean, onLoaded?: ()=>void }) {
  const [path, setPath] = useState("C:\\Users\\RDP\\Desktop\\model")
  const [status, setStatus] = useState<any>(null)
  const [validation, setValidation] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string|null>(null)

  const fetchStatus = async ()=>{ try{ setStatus(await getModelStatus()) }catch{} }
  useEffect(()=>{ fetchStatus(); const id=setInterval(fetchStatus, 4000); 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:"float16", quantization:"none", device_map:"cpu"}); setStatus(res); onLoaded?.()}catch(e:any){ setError(e.message)} finally{ setLoading(false)}
  }

  const isLoaded = status?.status==="loaded"

  if (compact) {
    return (
      <Card className="border-2">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm font-bold flex items-center gap-2"><FolderOpen className="h-4 w-4 text-violet-600"/> مسار مجلد النموذج</span>
            <Badge variant={isLoaded?"success":"destructive"}>{isLoaded?"محمل":"غير محمل"}</Badge>
          </div>
          <div className="flex gap-2">
            <Input value={path} onChange={e=>setPath(e.target.value)} placeholder="C:\Users\RDP\Desktop\model" className="flex-1 font-mono text-sm"/>
            <Button variant="outline" size="sm" onClick={handleValidate}>فحص</Button>
            <Button size="sm" onClick={handleLoad} disabled={loading} className="bg-violet-600 hover:bg-violet-700">{loading ? <Loader2 className="h-4 w-4 animate-spin"/> : "تحميل"}</Button>
          </div>
          {validation && (
            <div className={`rounded-lg border p-2 text-xs ${validation.valid?"bg-emerald-50 border-emerald-200":"bg-amber-50 border-amber-200"}`}>
              <div className="flex items-center gap-1 font-medium">{validation.valid?<CheckCircle2 className="h-3 w-3 text-emerald-600"/>:<AlertCircle className="h-3 w-3 text-amber-600"/>} {validation.reason}</div>
              {validation.details && <div className="text-zinc-500 mt-1">{validation.details.safetensors_count} ملفات • {validation.details.total_size_mb} MB</div>}
            </div>
          )}
          {error && <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded p-2">{error}</div>}
          {status && (
            <div className="flex flex-wrap gap-2 text-xs">
              <span className="px-2 py-1 rounded-full bg-zinc-100 border flex items-center gap-1"><HardDrive className="h-3 w-3"/> {status.model_type || "unknown"}</span>
              <span className="px-2 py-1 rounded-full bg-zinc-100 border">{status.num_parameters || "-"}</span>
              <span className="px-2 py-1 rounded-full bg-zinc-100 border flex items-center gap-1"><Cpu className="h-3 w-3"/> {status.dtype} {status.device_map}</span>
              {isLoaded && <span className="px-2 py-1 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-700">جاهز للاختبار ✓</span>}
            </div>
          )}
          {!isLoaded && <div className="text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded p-2">⚠️ النموذج غير محمل — الاختبار سيفشل. اضغط تحميل أو اذهب لـ <Link href="/models" className="underline">إدارة النماذج</Link></div>}
        </CardContent>
      </Card>
    )
  }

  // fallback to full ModelLoader if not compact
  return null
}
