import { api } from "@/lib/api"
import { useJobs, useQueryClient, qk } from "@/lib/queries"
import { useDialog } from "@/lib/useDialog"
import { cn } from "@/lib/utils"
import { fmtBytes, fmtEta } from "@/lib/format"

export function JobsBar() {
  const qc = useQueryClient()
  const { data: jobs = [] } = useJobs()
  const { showAlert, dialogElement } = useDialog()

  async function cancelJob(jobId: string) {
    try {
      await api(`/api/jobs/${jobId}/cancel`, { method: "POST" })
      qc.invalidateQueries({ queryKey: qk.jobs })
    } catch (e: any) {
      showAlert("Fehler", e.message)
    }
  }

  const active = jobs.filter((j) => j.state === "running" || j.state === "queued")
  const recent = jobs.filter((j) => j.state !== "running" && j.state !== "queued").slice(-3)

  if (active.length === 0 && recent.length === 0) return null

  return (
    <div className="space-y-3 mc-card p-4">
      <div className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">Aktive Downloads</div>

      {active.map((j) => (
        <div key={j.id} className="space-y-1.5 p-3 rounded-xl bg-background/20 border border-border/40">
          <div className="flex justify-between items-center text-xs">
            <span className="font-semibold truncate max-w-[250px]">{j.label}</span>
            <div className="flex items-center gap-3">
              <span className="text-muted-foreground font-mono">
                {j.progress ?? 0}% • {fmtBytes(j.done_bytes)}/{fmtBytes(j.total_bytes)}
                {j.eta_s ? ` • ETA ${fmtEta(j.eta_s)}` : ""}
              </span>
              <button
                onClick={() => cancelJob(j.id)}
                className="text-[10px] text-red-400 hover:text-red-300 font-semibold border border-red-500/25 bg-red-500/5 px-2 py-0.5 rounded transition-all cursor-pointer"
              >
                Abbrechen
              </button>
            </div>
          </div>
          <div className="h-1.5 overflow-hidden rounded-full bg-muted">
            <div className="h-full rounded-full bg-primary transition-all duration-500" style={{ width: `${j.progress ?? 0}%` }} />
          </div>
        </div>
      ))}

      {recent.map((j) => (
        <div key={j.id} className="flex justify-between items-center text-xs text-muted-foreground px-1">
          <span className="truncate">{j.label}</span>
          <span className={cn(
            "font-semibold text-[10px] px-1.5 py-0.5 rounded uppercase font-mono",
            j.state === "done" ? "bg-emerald-500/10 text-emerald-400" : "bg-amber-500/10 text-amber-400"
          )}>
            {j.state}
          </span>
        </div>
      ))}

      {dialogElement}
    </div>
  )
}
