import { useState } from "react"
import { Check, Copy, Terminal, Info, Globe, FolderOpen } from "lucide-react"
import { useConnect } from "@/lib/queries"
import { cn } from "@/lib/utils"

export function ConnectView() {
  const [host, setHost] = useState(localStorage.getItem("mc_host") || "192.168.178.151")
  const [mcpPath, setMcpPath] = useState(localStorage.getItem("mc_mcp_path") || "")
  const [active, setActive] = useState("cline")
  const [copied, setCopied] = useState(false)

  const params = new URLSearchParams({ host })
  if (mcpPath) params.set("mcp_path", mcpPath)
  const { data, error: dataErr } = useConnect(params.toString())
  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 tool = data?.tools[active]

  async function copy() {
    if (!tool) return
    await navigator.clipboard.writeText(tool.snippet)
    setCopied(true)
    setTimeout(() => setCopied(false), 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">
          Kopiere vorgefertigte Konfigurationsdateien für deinen lokalen PC (IDEs, Cline, Roo Code, Cursor), um direkt auf das geteilte Gedächtnis und den Auto-Swap-Gateway der Box zuzugreifen.
        </p>
      </div>

      {/* Connection Variables Panel */}
      <div className="grid gap-4 md:grid-cols-2 p-5 rounded-2xl border border-border/60 bg-card/45 backdrop-blur-md shadow-lg shadow-black/10">
        <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)}
            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-primary" /> Lokaler MCP-Scriptpfad
          </label>
          <input
            value={mcpPath}
            onChange={(e) => saveMcpPath(e.target.value)}
            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-primary/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-4">
          {/* Tool Tab Bar */}
          <div className="flex flex-wrap gap-1 bg-card/20 p-1 border border-border/40 rounded-xl max-w-fit">
            {Object.entries(data.tools).map(([key, t]) => (
              <button
                key={key}
                onClick={() => setActive(key)}
                className={cn(
                  "rounded-lg px-4 py-1.5 text-xs font-semibold tracking-wide uppercase transition-all cursor-pointer",
                  active === key 
                    ? "bg-primary text-primary-foreground shadow-md shadow-primary/10" 
                    : "text-muted-foreground hover:text-foreground",
                )}
              >
                {t.label}
              </button>
            ))}
          </div>

          {tool && (
            <div className="space-y-3">
              {/* Note / Info */}
              {tool.note && (
                <div className="flex items-start gap-2.5 p-3 rounded-xl bg-primary/5 border border-primary/20 text-xs text-muted-foreground leading-relaxed">
                  <Info className="h-4.5 w-4.5 text-primary shrink-0 mt-0.5" />
                  <span>{tool.note}</span>
                </div>
              )}

              {/* Editor Mockup Window */}
              <div className="flex flex-col border border-border/60 bg-black/60 rounded-2xl overflow-hidden shadow-2xl">
                {/* Editor Header Bar */}
                <div className="flex h-11 items-center justify-between px-4 border-b border-border/40 bg-black/40 shrink-0">
                  {/* Left: Window Control Dots */}
                  <div className="flex items-center gap-1.5">
                    <span className="h-3 w-3 rounded-full bg-red-500/80 shadow-md shadow-red-500/10" />
                    <span className="h-3 w-3 rounded-full bg-amber-500/80 shadow-md shadow-amber-500/10" />
                    <span className="h-3 w-3 rounded-full bg-emerald-500/80 shadow-md shadow-emerald-500/10" />
                  </div>
                  
                  {/* Center: File Title */}
                  <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">
                    <Terminal className="h-3.5 w-3.5 text-primary" />
                    <span>{active === "cline" || active === "cursor" ? "config.json" : "settings.json"}</span>
                  </div>

                  {/* Right: Copy Action */}
                  <button
                    onClick={copy}
                    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>

                {/* Editor Code Area */}
                <pre className="p-5 overflow-x-auto text-xs font-mono text-cyan-200/90 whitespace-pre leading-relaxed scrollbar-thin select-text bg-black/10">
                  <code>{tool.snippet}</code>
                </pre>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
