import { useState } from "react"
import {
  Check, Copy, Cpu, Brain, Globe, FolderOpen, Laptop, ArrowRight,
  Info, CircleCheck, CircleX, Loader2, ChevronDown, ChevronRight,
} from "lucide-react"
import { useConnect, useConnectHealth } from "@/lib/queries"
import type { ConnectTool, ConnectLine } from "@/lib/api"
import { cn } from "@/lib/utils"

// Dateiziel je Tool — nur Hinweis im Editor-Kopf, keine Logik.
const FILE_NAMES: Record<string, string> = {
  hermes_desktop: "Hermes Desktop: Browser-Login",
  kilo: "Kilo: Einstellungen → API Provider",
  claude_code: "env / Übersetzer",
}

function StatusBadge({ line, loading }: { line?: ConnectLine; loading: boolean }) {
  if (loading || !line) {
    return (
      <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-muted-foreground">
        <Loader2 className="h-3 w-3 animate-spin" /> prüfe…
      </span>
    )
  }
  return line.ok ? (
    <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-emerald-400">
      <CircleCheck className="h-3 w-3" /> {line.detail}
    </span>
  ) : (
    <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-red-400">
      <CircleX className="h-3 w-3" /> {line.detail}
    </span>
  )
}

// Schwarzes „Editor-Fenster" mit Ampel-Dots + Kopieren-Knopf.
function CodeWindow({
  tool, fileName, accent, copied, onCopy,
}: {
  tool: ConnectTool
  fileName: string
  accent: "teal" | "violet"
  copied: boolean
  onCopy: () => void
}) {
  return (
    <div className="flex flex-col border border-border/60 bg-black/60 rounded-2xl overflow-hidden shadow-2xl">
      <div className="flex h-11 items-center justify-between px-4 border-b border-border/40 bg-black/40 shrink-0">
        <div className="flex items-center gap-1.5">
          <span className="h-3 w-3 rounded-full bg-red-500/80" />
          <span className="h-3 w-3 rounded-full bg-amber-500/80" />
          <span className="h-3 w-3 rounded-full bg-emerald-500/80" />
        </div>
        <div className="flex items-center gap-1.5 text-[10px] font-mono text-muted-foreground/75 bg-background/30 px-3 py-1 rounded-md border border-border/20">
          <span>{fileName}</span>
        </div>
        <button
          onClick={onCopy}
          className="flex h-7 px-2.5 items-center gap-1.5 rounded-lg border border-border/40 bg-background/30 text-[10px] font-semibold text-muted-foreground hover:text-foreground hover:bg-background/60 transition-all cursor-pointer"
        >
          {copied ? <Check className="h-3.5 w-3.5 text-emerald-400" /> : <Copy className="h-3.5 w-3.5" />}
          <span>{copied ? "Kopiert" : "Kopieren"}</span>
        </button>
      </div>
      <pre className={cn(
        "p-5 overflow-x-auto text-xs font-mono whitespace-pre leading-relaxed scrollbar-thin select-text bg-black/10",
        accent === "teal" ? "text-cyan-200/90" : "text-violet-200/90",
      )}>
        <code>{tool.snippet}</code>
      </pre>
    </div>
  )
}

export function ConnectView() {
  const [host, setHost] = useState(localStorage.getItem("mc_host") || "192.168.178.151")
  const [mcpPath, setMcpPath] = useState(localStorage.getItem("mc_mcp_path") || "")
  // Legacy-Tools (roher /v1-Zugang) leben im Ausklapper — Hermes Desktop ist der Hauptweg.
  const [active, setActive] = useState("kilo")
  const [sonstigeOffen, setSonstigeOffen] = useState(false)
  const [copied, setCopied] = useState<"desktop" | "model" | "memory" | null>(null)

  const params = new URLSearchParams({ host })
  if (mcpPath) params.set("mcp_path", mcpPath)
  const { data, error: dataErr } = useConnect(params.toString())
  const { data: health, isLoading: healthLoading } = useConnectHealth()
  const error = dataErr ? String(dataErr) : ""

  function saveHost(v: string) {
    setHost(v)
    if (v) localStorage.setItem("mc_host", v)
  }

  function saveMcpPath(v: string) {
    setMcpPath(v)
    localStorage.setItem("mc_mcp_path", v)
  }

  const desktop = data?.tools["hermes_desktop"]
  const tool = data?.tools[active]

  async function copy(which: "desktop" | "model" | "memory", snippet?: string) {
    if (!snippet) return
    await navigator.clipboard.writeText(snippet)
    setCopied(which)
    setTimeout(() => setCopied(null), 1500)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-space font-bold tracking-tight bg-gradient-to-r from-foreground via-foreground to-primary bg-clip-text text-transparent">
          Verbindung &amp; Integration
        </h1>
        <p className="text-sm text-muted-foreground">
          <span className="text-foreground">Hermes Desktop</span> ist die Tür zur Box — einmal verbinden, fertig.
          Für Spezialfälle gibt es darunter die rohen Leitungen (Gateway&nbsp;/v1 + Gedächtnis-MCP) für sonstige Tools.
        </p>
      </div>

      {/* Hero: die zwei Leitungen */}
      <div className="p-5 mc-card">
        <div className="grid gap-4 md:grid-cols-[170px_1fr] items-center">
          {/* Lokaler Agent */}
          <div className="rounded-2xl border border-border/60 bg-background/40 p-4 text-center">
            <Laptop className="h-7 w-7 mx-auto text-muted-foreground" />
            <div className="mt-2 text-sm font-semibold text-foreground">Dein lokaler Agent</div>
            <div className="text-[11px] text-muted-foreground">Hermes Desktop · Kilo Code · Claude Code …</div>
          </div>

          {/* Zwei Leitungen */}
          <div className="flex flex-col gap-2.5">
            {/* Leitung 1 — Modell */}
            <div className="flex items-center gap-3">
              <ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
              <div className="flex-1 rounded-xl border border-primary/25 bg-primary/5 px-3.5 py-2.5">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 text-xs font-semibold text-primary">
                    <Cpu className="h-3.5 w-3.5" /> Leitung 1 — Modell
                  </div>
                  <StatusBadge line={health?.gateway} loading={healthLoading} />
                </div>
                <div className="mt-1 text-[11px] font-mono text-primary/80">
                  Gateway · :9001/v1 · Lanes chat / coding
                </div>
              </div>
            </div>
            {/* Leitung 2 — Gedächtnis */}
            <div className="flex items-center gap-3">
              <ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
              <div className="flex-1 rounded-xl border border-violet-500/25 bg-violet-500/5 px-3.5 py-2.5">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 text-xs font-semibold text-violet-300">
                    <Brain className="h-3.5 w-3.5" /> Leitung 2 — Gedächtnis
                  </div>
                  <StatusBadge line={health?.memory} loading={healthLoading} />
                </div>
                <div className="mt-1 text-[11px] font-mono text-violet-300/80">
                  MCP · mcp_memory.py · separat
                </div>
              </div>
            </div>
            {/* Leitung 3 — Desktop-Gateway */}
            <div className="flex items-center gap-3">
              <ArrowRight className="h-4 w-4 text-muted-foreground shrink-0" />
              <div className="flex-1 rounded-xl border border-emerald-500/25 bg-emerald-500/5 px-3.5 py-2.5">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 text-xs font-semibold text-emerald-300">
                    <Laptop className="h-3.5 w-3.5" /> Leitung 3 — Desktop-Gateway
                  </div>
                  <StatusBadge line={health?.desktop_gateway} loading={healthLoading} />
                </div>
                <div className="mt-1 text-[11px] font-mono text-emerald-300/80">
                  Desktop-Gateway · :9119 · API-Status
                </div>
              </div>
            </div>
          </div>
        </div>
        <p className="mt-3.5 text-[11px] text-muted-foreground leading-relaxed">
          Der Gateway liefert <span className="text-foreground">nur das LLM</span>. Das geteilte Gedächtnis läuft über einen
          <span className="text-foreground"> eigenen MCP-Server</span> und das Desktop-Gateway bietet die Agenten-Schnittstelle —
          alle drei Leitungen werden unabhängig eingerichtet.
        </p>
      </div>

      {/* Gemeinsame Variablen */}
      <div className="grid gap-4 md:grid-cols-2 p-5 mc-card">
        <div className="space-y-1.5">
          <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
            <Globe className="h-3.5 w-3.5 text-primary" /> Box LAN IP-Adresse
          </label>
          <input
            value={host}
            onChange={(e) => saveHost(e.target.value)}
            aria-label="Box LAN IP-Adresse"
            spellCheck={false}
            placeholder="z.B. 192.168.178.151"
            className="w-full h-9 rounded-lg border border-border/60 bg-background/40 px-3 font-mono text-xs outline-none focus:ring-1 focus:ring-primary/50 text-foreground"
          />
        </div>

        <div className="space-y-1.5">
          <label className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
            <FolderOpen className="h-3.5 w-3.5 text-violet-400" /> Lokaler MCP-Scriptpfad
            <span className="text-violet-400/70 normal-case font-semibold tracking-normal">(nur Leitung 2)</span>
          </label>
          <input
            value={mcpPath}
            onChange={(e) => saveMcpPath(e.target.value)}
            aria-label="Lokaler MCP-Scriptpfad"
            spellCheck={false}
            placeholder="z.B. F:\Coding Stuff\mission-control-2\mcp\mcp_memory.py"
            className="w-full h-9 rounded-lg border border-border/60 bg-background/40 px-3 font-mono text-xs outline-none focus:ring-1 focus:ring-violet-500/50 text-foreground"
          />
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/5 p-4 text-xs text-red-400">
          Fehler beim Generieren der Snippets: {error}
        </div>
      )}

      {data && (
        <div className="space-y-5">
          {/* Hauptweg — Hermes Desktop anbinden */}
          {desktop && (
            <div className="space-y-3 rounded-2xl border border-border/60 border-t-2 border-t-emerald-500/70 bg-card/30 p-4">
              <div>
                <div className="flex items-center gap-2 text-sm font-space font-bold text-foreground">
                  <Laptop className="h-4 w-4 text-emerald-400" />
                  Hermes Desktop anbinden
                  <span className="text-[10px] font-medium text-emerald-400/90 normal-case">der Hauptweg</span>
                </div>
                <p className="text-[11px] text-muted-foreground mt-0.5">
                  Die Desktop-App dockt remote an die Box an — volle Agent-Oberfläche, Projekte, Review, Gedächtnis inklusive.
                </p>
              </div>
              {desktop.note && (
                <div className="flex items-start gap-2.5 p-3 rounded-xl bg-emerald-500/5 border border-emerald-500/20 text-[11px] text-muted-foreground leading-relaxed">
                  <Info className="h-4 w-4 text-emerald-400 shrink-0 mt-0.5" />
                  <span>{desktop.note}</span>
                </div>
              )}
              <CodeWindow
                tool={desktop}
                fileName={FILE_NAMES["hermes_desktop"]}
                accent="teal"
                copied={copied === "desktop"}
                onCopy={() => copy("desktop", desktop.snippet)}
              />
            </div>
          )}

          {/* Ausklapper — Legacy: roher /v1-Zugang + Gedächtnis-MCP für sonstige Tools */}
          <div className="rounded-2xl border border-border/60 bg-card/30">
            <button
              onClick={() => setSonstigeOffen((v) => !v)}
              className="flex w-full items-center gap-2 p-4 text-sm font-space font-bold text-foreground cursor-pointer hover:text-primary transition-colors"
            >
              {sonstigeOffen ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
              Sonstige Tools (roher /v1-Zugang + Gedächtnis-MCP)
              <span className="text-[10px] font-medium text-muted-foreground normal-case">Kilo Code · Claude Code · Eigenbau</span>
            </button>

            {sonstigeOffen && (
              <div className="grid gap-5 lg:grid-cols-2 p-4 pt-0">
                {/* Leitung 1 — Modell anbinden */}
                <div className="space-y-3 rounded-2xl border border-border/60 border-t-2 border-t-primary/70 bg-card/30 p-4">
                  <div>
                    <div className="flex items-center gap-2 text-sm font-space font-bold text-foreground">
                      <span className="flex h-5 w-5 items-center justify-center rounded-md bg-primary/15 text-primary text-[11px]">1</span>
                      Modell anbinden
                    </div>
                    <p className="text-[11px] text-muted-foreground mt-0.5">Wähle dein Tool — das Snippet zeigt auf den Gateway.</p>
                  </div>

                  {/* Tool-Picker (ohne hermes_desktop — der hat oben seine eigene Karte) */}
                  <div className="flex flex-wrap gap-1.5">
                    {Object.entries(data.tools).filter(([key]) => key !== "hermes_desktop").map(([key, t]) => (
                      <button
                        key={key}
                        onClick={() => setActive(key)}
                        className={cn(
                          "rounded-lg px-3 py-1.5 text-[11px] font-semibold tracking-wide transition-all cursor-pointer",
                          active === key
                            ? "bg-primary text-primary-foreground shadow-md shadow-primary/10"
                            : "border border-border/50 text-muted-foreground hover:text-foreground",
                        )}
                      >
                        {t.label}
                      </button>
                    ))}
                  </div>

                  {tool && (
                    <>
                      {tool.note && (
                        <div className="flex items-start gap-2.5 p-3 rounded-xl bg-primary/5 border border-primary/20 text-[11px] text-muted-foreground leading-relaxed">
                          <Info className="h-4 w-4 text-primary shrink-0 mt-0.5" />
                          <span>{tool.note}</span>
                        </div>
                      )}
                      <CodeWindow
                        tool={tool}
                        fileName={FILE_NAMES[active] || "config.json"}
                        accent="teal"
                        copied={copied === "model"}
                        onCopy={() => copy("model", tool.snippet)}
                      />
                    </>
                  )}
                </div>

                {/* Leitung 2 — Gedächtnis anbinden */}
                <div className="space-y-3 rounded-2xl border border-border/60 border-t-2 border-t-violet-500/70 bg-card/30 p-4">
                  <div>
                    <div className="flex items-center gap-2 text-sm font-space font-bold text-foreground">
                      <span className="flex h-5 w-5 items-center justify-center rounded-md bg-violet-500/15 text-violet-300 text-[11px]">2</span>
                      Gedächtnis anbinden
                      <span className="text-[10px] font-medium text-muted-foreground normal-case">optional</span>
                    </div>
                    <p className="text-[11px] text-muted-foreground mt-0.5">Ein MCP-Block — gilt zusätzlich für <em>jedes</em> Tool aus Schritt 1.</p>
                  </div>

                  <div className="flex items-start gap-2.5 p-3 rounded-xl bg-violet-500/5 border border-violet-500/20 text-[11px] text-muted-foreground leading-relaxed">
                    <Info className="h-4 w-4 text-violet-400 shrink-0 mt-0.5" />
                    <span>{data.memory.note}</span>
                  </div>

                  <CodeWindow
                    tool={data.memory}
                    fileName="mcp.json"
                    accent="violet"
                    copied={copied === "memory"}
                    onCopy={() => copy("memory", data.memory.snippet)}
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
