"use client"
import { useState } 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 { scanCustomFolder, runCustomFromFolder, uploadCustomDataset, getCustomFormats } from "@/lib/api"
import { API_BASE } from "@/lib/utils"
import { Upload, FolderOpen, Loader2, FileText, Languages, CheckCircle2, Play, BarChart3 } from "lucide-react"

export function CustomDatasetPanel({ onReport }: { onReport: (r:any)=>void }) {
  const [folderPath, setFolderPath] = useState("C:\\data\\my-dataset")
  const [scan, setScan] = useState<any>(null)
  const [scanning, setScanning] = useState(false)
  const [running, setRunning] = useState(false)
  const [error, setError] = useState<string|null>(null)
  const [judge, setJudge] = useState("regex")
  const [formats, setFormats] = useState<any>(null)

  const handleScan = async ()=>{
    setScanning(true); setError(null)
    try{
      const res = await scanCustomFolder(folderPath)
      setScan(res)
    } catch(e:any){ setError(e.message)}
    finally{ setScanning(false)}
  }
  const handleRunFolder = async ()=>{
    setRunning(true); setError(null)
    try{
      const res = await runCustomFromFolder(folderPath, judge)
      onReport(res.report)
      setScan((s:any)=>({...s, lastMeta: res.meta}))
    } catch(e:any){ setError(e.message)}
    finally{ setRunning(false)}
  }
  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>)=>{
    const files = e.target.files
    if (!files || files.length===0) return
    setRunning(true); setError(null)
    try{
      const res = await uploadCustomDataset(files, judge)
      onReport(res.report)
    } catch(e:any){ setError(e.message)}
    finally{ setRunning(false)}
  }
  const showFormats = async ()=>{
    try{ setFormats(await getCustomFormats()) }catch{}
  }

  return (
    <Card className="border-2 border-violet-200 dark:border-violet-900">
      <CardHeader>
        <CardTitle className="flex items-center gap-2"><FolderOpen className="h-5 w-5 text-violet-600"/> بياناتك المخصصة — مجلد كامل بصيغ متنوعة</CardTitle>
        <CardDescription>يدعم <code>.csv .json .jsonl .txt .md</code> — النظام يكشف العربية/الإنجليزية تلقائياً ويصنف الفئة (reasoning/coding/arabic/summarization)</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Upload */}
        <div className="grid md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <label className="text-sm font-medium flex items-center gap-2"><FolderOpen className="h-4 w-4"/> مسار مجلد محلي (على الخادم)</label>
            <div className="flex gap-2">
              <Input value={folderPath} onChange={e=>setFolderPath(e.target.value)} placeholder="C:\data\my-dataset أو /home/user/dataset" className="font-mono text-sm"/>
              <Button variant="outline" onClick={handleScan} disabled={scanning}>{scanning ? <Loader2 className="h-4 w-4 animate-spin"/> : "فحص"}</Button>
            </div>
            <p className="text-xs text-zinc-500">المجلد يجب أن يكون على نفس جهاز الـ Backend (مثل مجلد النموذج)</p>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium flex items-center gap-2"><Upload className="h-4 w-4"/> أو رفع ملفات مباشرة</label>
            <label className="flex items-center justify-center gap-2 border-2 border-dashed rounded-xl p-4 cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-900">
              <Upload className="h-4 w-4"/> اختر ملفات (.csv/.json/.jsonl/.txt)
              <input type="file" multiple accept=".csv,.json,.jsonl,.txt,.md" className="hidden" onChange={handleUpload}/>
            </label>
            <p className="text-xs text-zinc-500">يدعم رفع متعدد + مجلدات via drag & drop (webkitdirectory)</p>
          </div>
        </div>

        <div className="flex flex-wrap gap-2 items-center">
          <span className="text-sm font-medium">طريقة التقييم:</span>
          {["regex","exact","llm"].map(m=> <button key={m} onClick={()=>setJudge(m)} className={`px-3 py-1.5 rounded-full text-xs border ${judge===m?"bg-violet-600 text-white border-violet-600":"bg-white"}`}>{m}</button>)}
          <Button size="sm" variant="ghost" onClick={showFormats} className="text-xs">عرض الصيغ المدعومة</Button>
        </div>
        {formats && (
          <div className="rounded-lg bg-zinc-50 dark:bg-zinc-900 border p-3 text-xs space-y-1">
            <div><b>الصيغ:</b> {formats.formats.join(", ")}</div>
            <div><b>CSV columns:</b> {formats.columns_csv[0]}</div>
            <div className="font-mono bg-white dark:bg-zinc-800 p-2 rounded border overflow-x-auto">{JSON.stringify(formats.json_example, null, 2)}</div>
            <div className="text-zinc-500">{formats.detection}</div>
          </div>
        )}

        {error && <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">{error}</div>}

        {scan && (
          <div className="rounded-xl border bg-zinc-50 dark:bg-zinc-900 p-4 space-y-3">
            <div className="flex flex-wrap gap-2 items-center">
              <Badge variant="secondary"><FileText className="h-3 w-3 me-1"/> {scan.files_found} ملفات</Badge>
              <Badge variant="secondary"><BarChart3 className="h-3 w-3 me-1"/> {scan.total_tasks} مهمة</Badge>
              <Badge variant="outline" className="flex items-center gap-1"><Languages className="h-3 w-3"/> عربي: {scan.language_counts.ar} | إنجليزي: {scan.language_counts.en}</Badge>
              {scan.language_counts.ar && scan.language_counts.en ? <Badge variant="warning">مختلط</Badge> : scan.language_counts.ar ? <Badge variant="success">عربي</Badge> : <Badge>إنجليزي</Badge>}
            </div>
            <div className="grid md:grid-cols-2 gap-2 text-xs">
              {Object.entries(scan.per_file_counts).map(([k,v]:any)=>(
                <div key={k} className="flex justify-between p-2 bg-white dark:bg-zinc-800 rounded border"><span className="truncate me-2">{k}</span><span>{String(v)}</span></div>
              ))}
            </div>
            {scan.preview && scan.preview.length>0 && (
              <div className="space-y-1">
                <div className="text-xs font-medium">معاينة (5 مهام أولى):</div>
                {scan.preview.map((r:any,i:number)=>(
                  <div key={i} className="p-2 bg-white dark:bg-zinc-800 rounded border text-xs">
                    <div className="flex gap-2"><Badge variant="secondary" className="text-[10px]">{r.category}</Badge><Badge variant="outline" className="text-[10px]">{r.language}</Badge><span className="text-zinc-500 truncate">{r.prompt.slice(0,80)}</span></div>
                    {r.expected && <div className="text-zinc-600 mt-1">المتوقع: {r.expected.slice(0,60)}</div>}
                  </div>
                ))}
              </div>
            )}
            <Button onClick={handleRunFolder} disabled={running} className="w-full bg-gradient-to-r from-violet-600 to-indigo-600">
              {running ? <><Loader2 className="h-4 w-4 animate-spin me-2"/> جاري الاختبار...</> : <><Play className="h-4 w-4 me-2"/> شغّل الاختبار على هذه البيانات ({scan.total_tasks} مهمة)</>}
            </Button>
          </div>
        )}

        <div className="rounded-lg border bg-amber-50 dark:bg-amber-950/20 p-3 text-xs space-y-1">
          <div className="font-medium flex items-center gap-1"><CheckCircle2 className="h-3 w-3"/> كيف يكشف اللغة؟</div>
          <div>• وجود حروف <code>\u0600-\u06FF</code> → عربي، وإلا إنجليزي — يُحسب لكل prompt تلقائياً ويظهر في `language_counts`.</div>
          <div>• الفئة تُستنتج من كلمات مثل <code>code/كود/python</code> → coding، <code>لخص/summarize</code> → summarization، وإلا حسب اللغة.</div>
          <div>• مثال CSV: <code>prompt,expected,category</code> — إذا تركت `category` فارغ يملأ تلقائياً.</div>
        </div>
      </CardContent>
    </Card>
  )
}
