import { useState } from "react"
import { HeartPulse, HardDrive, Wrench, Check, AlertTriangle, Loader2, ShieldQuestion } from "lucide-react"
import { api } from "@/lib/api"
import { useDialog } from "@/lib/useDialog"
import { useQueryClient, qk } from "@/lib/queries"
import { useLucyHealth, type LucyCheck, type Repair } from "@/lib/useLucyHealth"
import { cn } from "@/lib/utils"

// Farb-/Text-Ton pro Check-Status.
const DOT: Record<string, string> = {
  ok: "bg-emerald-500",
  warn: "bg-amber-500",
  down: "bg-red-500",
  loading: "bg-muted-foreground/40",
}

// `frame` = Erzählrahmen: "lucy" (MC2-Dashboard) oder "box" (MC3-Basisstation).
export function LucyHealthCard({ frame = "lucy" }: { frame?: "lucy" | "box" } = {}) {
  const { verdict, checks, memory, problems } = useLucyHealth()
  const { showAlert, dialogElement } = useDialog()
  const qc = useQueryClient()
  const [busy, setBusy] = useState<Record<string, boolean>>({})

  async function runRepair(id: string, repair: Repair) {
    setBusy((b) => ({ ...b, [id]: true }))
    try {
      if (repair.kind === "loadModel") {
        await api(`/api/models/${encodeURIComponent(repair.model)}/load`, { method: "POST" })
      } else {
        const r = await api<{ ok: boolean; err?: string }>("/api/maintenance/restart", {
          method: "POST",
          body: JSON.stringify({ service: repair.service }),
        })
        if (!r.ok) {
          showAlert(
            "Reparatur nicht ganz geklappt",
            (r.err || "Unbekannter Fehler") +
              (repair.needsSudo ? "\n\nTipp: Dafür wird evtl. das Box-Passwort gebraucht (oben rechts hinterlegen)." : ""),
          )
        }
      }
      // Status-Queries neu ziehen, damit die Ampel sich sofort aktualisiert.
      qc.invalidateQueries({ queryKey: qk.health })
      qc.invalidateQueries({ queryKey: qk.services })
      qc.invalidateQueries({ queryKey: qk.models })
    } catch (e: any) {
      showAlert("Reparatur fehlgeschlagen", String(e?.message || e))
    } finally {
      setBusy((b) => ({ ...b, [id]: false }))
    }
  }

  // Titel je Erzählrahmen (Box-Kontrollpanel vs. Lucy-Dashboard).
  const T = frame === "box"
    ? { loading: "Box wird geprüft …", gut: "Alles okay", warn: "Kleinigkeit an der Box", problem: "Box braucht Hilfe" }
    : { loading: "Lucy wird geprüft …", gut: "Lucy geht's gut 💚", warn: "Kleinigkeit bei Lucy", problem: "Lucy braucht Hilfe" }

  // Banner-Optik je Gesamt-Verdikt.
  const banner = {
    loading: { ring: "border-border/60 bg-card/45", icon: Loader2, iconCls: "text-muted-foreground animate-spin", title: T.loading, sub: "Einen Moment, ich schaue nach dem Rechten." },
    gut: { ring: "border-emerald-500/40 bg-emerald-500/5", icon: HeartPulse, iconCls: "text-emerald-400", title: T.gut, sub: "Alle wichtigen Fähigkeiten laufen." },
    warn: { ring: "border-amber-500/40 bg-amber-500/5", icon: AlertTriangle, iconCls: "text-amber-400", title: T.warn, sub: "Nichts Schlimmes — nur ein Hinweis." },
    problem: { ring: "border-red-500/50 bg-red-500/5", icon: AlertTriangle, iconCls: "text-red-400", title: T.problem, sub: `${problems.length} wichtige${problems.length === 1 ? "s" : ""} Problem${problems.length === 1 ? "" : "e"} gefunden.` },
  }[verdict]
  const BannerIcon = banner.icon

  const memTone = {
    ok: "bg-emerald-500", warn: "bg-amber-500", full: "bg-red-500", unknown: "bg-muted-foreground/40",
  }[memory.status]
  const memText = {
    ok: "text-emerald-400", warn: "text-amber-400", full: "text-red-400", unknown: "text-muted-foreground",
  }[memory.status]

  return (
    <div className={cn("rounded-2xl border p-5 shadow-lg shadow-black/15 backdrop-blur-md transition-colors", banner.ring)}>
      {/* Gesamt-Verdikt */}
      <div className="flex items-center gap-3">
        <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-border/40 bg-background/30">
          <BannerIcon className={cn("h-6 w-6", banner.iconCls)} />
        </div>
        <div className="min-w-0">
          <h2 className="text-base font-bold tracking-tight text-foreground">{banner.title}</h2>
          <p className="text-xs text-muted-foreground">{banner.sub}</p>
        </div>
      </div>

      {/* Speicher-Ampel */}
      <div className="mt-4 rounded-xl border border-border/30 bg-background/20 p-3">
        <div className="mb-1.5 flex items-center justify-between text-[11px]">
          <span className="flex items-center gap-1.5 font-semibold uppercase tracking-wider text-muted-foreground">
            <HardDrive className="h-3.5 w-3.5" /> Speicher
          </span>
          <span className={cn("font-mono font-bold", memText)}>
            {memory.status === "unknown" ? "—" : `${memory.usedGb.toFixed(0)} / ${memory.totalGb.toFixed(0)} GB`}
          </span>
        </div>
        <div className="h-2 w-full overflow-hidden rounded-full border border-border/30 bg-background/50">
          <div className={cn("h-full rounded-full transition-all duration-500", memTone)} style={{ width: `${memory.pct}%` }} />
        </div>
        <p className={cn("mt-1.5 text-[11px]", memText)}>{memory.text}</p>
      </div>

      {/* Fähigkeiten-Checkliste */}
      <div className="mt-4 space-y-1.5">
        {checks.map((c) => (
          <CheckRow key={c.id} c={c} busy={!!busy[c.id]} onRepair={() => c.repair && runRepair(c.id, c.repair)} />
        ))}
      </div>

      {dialogElement}
    </div>
  )
}

function CheckRow({ c, busy, onRepair }: { c: LucyCheck; busy: boolean; onRepair: () => void }) {
  const Icon = c.icon
  const bad = c.status === "down" || c.status === "warn"
  return (
    <div
      className={cn(
        "flex items-center justify-between gap-3 rounded-xl border p-2.5 transition-colors",
        c.status === "down" ? "border-red-500/25 bg-red-500/5"
          : c.status === "warn" ? "border-amber-500/20 bg-amber-500/5"
            : "border-border/30 bg-background/15",
      )}
    >
      <div className="flex min-w-0 items-center gap-2.5">
        <span className="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border/40 bg-background/30 text-foreground/80">
          <Icon className="h-4 w-4" />
          <span className={cn("absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full ring-2 ring-black/40", DOT[c.status], c.status === "down" && "animate-pulse")} />
        </span>
        <div className="min-w-0">
          <div className="flex items-center gap-1.5 text-xs font-bold text-foreground">
            {c.label}
            {c.status === "ok" && <Check className="h-3 w-3 text-emerald-400" />}
            {!c.critical && <span className="rounded bg-background/40 px-1 py-0.5 text-[8px] font-semibold uppercase tracking-wider text-muted-foreground/60">optional</span>}
          </div>
          <div className="truncate text-[11px] text-muted-foreground">{c.detail}</div>
        </div>
      </div>

      {bad && c.repair && (
        <button
          onClick={onRepair}
          disabled={busy}
          className={cn(
            "flex h-8 shrink-0 items-center gap-1.5 rounded-lg border px-2.5 text-[10px] font-bold uppercase tracking-wide transition-all cursor-pointer disabled:opacity-60",
            c.status === "down"
              ? "border-red-500/40 bg-red-500/10 text-red-300 hover:bg-red-500/20"
              : "border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20",
          )}
          title={c.repair.label}
        >
          {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Wrench className="h-3.5 w-3.5" />}
          {c.repair.label}
        </button>
      )}
      {bad && !c.repair && (
        <span className="flex shrink-0 items-center gap-1 text-[10px] font-semibold text-muted-foreground" title="Keine Auto-Reparatur bekannt">
          <ShieldQuestion className="h-3.5 w-3.5" /> manuell
        </span>
      )}
    </div>
  )
}
