import { useEffect, useState } from "react"
import { Command as CommandIcon, ChevronLeft, ChevronRight } from "lucide-react"
import { NAV, type ViewId } from "@/nav"
import { CommandPalette } from "@/components/CommandPalette"
import { DashboardView } from "@/views/DashboardView"
import { ModelsView } from "@/views/ModelsView"
import { ConnectView } from "@/views/ConnectView"
import { MemoryView } from "@/views/MemoryView"
import { AgentView } from "@/views/AgentView"
import { TerminalView } from "@/views/TerminalView"
import { GuideView } from "@/views/GuideView"
import { Placeholder } from "@/views/Placeholder"
import { SystemDrawer } from "@/components/SystemDrawer"
import { useHealth, useSystemStatus } from "@/lib/queries"
import { useMetricsFeeder } from "@/lib/metricsStore"
import { cn } from "@/lib/utils"

export default function App() {
  useMetricsFeeder()   // sammelt Live-Verlauf global, unabhängig vom aktiven Tab
  const [view, setView] = useState<ViewId>("dashboard")
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => localStorage.getItem("mc_sidebar_collapsed") === "true")
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [drawerTab, setDrawerTab] = useState<"maintenance" | "logs">("maintenance")

  const { data: health } = useHealth()
  const { data: sysStatus } = useSystemStatus(20_000)

  useEffect(() => {
    document.documentElement.classList.add("dark")
  }, [])

  useEffect(() => {
    const handleOpen = (e: Event) => {
      const customEvent = e as CustomEvent
      setDrawerTab(customEvent.detail?.tab || "maintenance")
      setDrawerOpen(true)
    }
    window.addEventListener("open-system-drawer", handleOpen)
    return () => window.removeEventListener("open-system-drawer", handleOpen)
  }, [])

  const active = NAV.find((n) => n.id === view)!

  return (
    <div className="flex h-full relative">
      {/* Background Aurora Ambient Effects */}
      <div className="fixed inset-0 -z-50 pointer-events-none overflow-hidden bg-[hsl(224,30%,6%)]">
        <div className="absolute inset-0 opacity-35 animate-aurora bg-gradient-to-tr from-teal-500/20 via-indigo-500/15 to-purple-500/20 blur-[130px]" />
        <div className="absolute top-[-10%] left-[-10%] h-[50%] w-[50%] rounded-full bg-teal-500/15 blur-[160px]" />
        <div className="absolute bottom-[-10%] right-[-10%] h-[50%] w-[50%] rounded-full bg-purple-500/15 blur-[160px]" />
        <div className="absolute top-[30%] right-[20%] h-[40%] w-[40%] rounded-full bg-indigo-500/10 blur-[140px]" />
      </div>

      <CommandPalette onNavigate={setView} />
      <SystemDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} defaultTab={drawerTab} />

      {/* Sidebar */}
      <aside className={cn(
        "flex shrink-0 flex-col border-r border-border/40 bg-card/45 backdrop-blur-md transition-all duration-300 ease-in-out",
        sidebarCollapsed ? "w-16" : "w-60"
      )}>
        <div className={cn("flex items-center py-4 border-b border-border/40 shrink-0", sidebarCollapsed ? "flex-col gap-3 px-2" : "justify-between px-5")}>
          <div className="flex items-center gap-2 overflow-hidden">
            <div className="h-7 w-7 rounded-lg bg-primary shadow-md shadow-primary/20 shrink-0" />
            {!sidebarCollapsed && (
              <div className="leading-tight">
                <div className="text-sm font-semibold tracking-wide font-space">Mission Control</div>
                <div className="text-xs text-muted-foreground">2.0</div>
              </div>
            )}
          </div>
          <button 
            onClick={() => {
              setSidebarCollapsed(c => {
                const next = !c
                localStorage.setItem("mc_sidebar_collapsed", next.toString())
                return next
              })
            }}
            className="p-1 rounded-md hover:bg-accent text-muted-foreground transition-colors cursor-pointer"
            title={sidebarCollapsed ? "Maximieren" : "Minimieren"}
          >
            {sidebarCollapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
          </button>
        </div>
        
        <nav className="flex-1 space-y-1 px-3 py-4 overflow-y-auto">
          {NAV.map((item) => (
            <button
              key={item.id}
              onClick={() => setView(item.id)}
              className={cn(
                "flex w-full items-center rounded-md text-sm transition-all cursor-pointer",
                sidebarCollapsed ? "justify-center p-2.5" : "gap-3 px-3 py-2",
                view === item.id
                  ? "bg-primary/15 text-primary shadow-sm shadow-primary/5"
                  : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
              )}
              title={sidebarCollapsed ? item.label : undefined}
            >
              <item.icon className="h-4.5 w-4.5 shrink-0" />
              {!sidebarCollapsed && <span className="truncate">{item.label}</span>}
            </button>
          ))}
        </nav>

        <div className={cn("py-3 text-xs text-muted-foreground border-t border-border/40 shrink-0", sidebarCollapsed ? "px-2 text-center" : "px-5")}>
          {sidebarCollapsed ? (
            <div className="flex justify-center">
              <span className={cn(
                "h-2.5 w-2.5 rounded-full ring-2 ring-black/40",
                health ? (health.engine_reachable ? "bg-emerald-500 animate-pulse" : "bg-amber-500") : "bg-red-500"
              )} title={health ? `Engine ${health.engine_reachable ? "online" : "offline"}` : "Backend offline"} />
            </div>
          ) : (
            <div className="space-y-2 text-left">
              {health ? (
                <span className="flex items-center gap-2">
                  <span className={cn("h-2 w-2 rounded-full animate-pulse", health.engine_reachable ? "bg-emerald-500" : "bg-amber-500")} />
                  <span className="truncate">Engine {health.engine_reachable ? "online" : "offline"}</span>
                </span>
              ) : (
                <span className="flex items-center gap-2">
                  <span className="h-2 w-2 rounded-full bg-red-500" /> <span className="truncate">Backend offline</span>
                </span>
              )}
              
              {sysStatus?.versions && (
                <div className="space-y-1 text-[9px] text-muted-foreground/60 mt-2 pt-2 border-t border-border/30">
                  <div className="truncate" title={sysStatus.versions.mc2 ? `${sysStatus.versions.mc2.branch}-${sysStatus.versions.mc2.hash}${sysStatus.versions.mc2.dirty ? "*" : ""} (${sysStatus.versions.mc2.date})` : "nicht gefunden"}>
                    <strong>MC2:</strong> {sysStatus.versions.mc2 ? `${sysStatus.versions.mc2.hash}${sysStatus.versions.mc2.dirty ? "*" : ""}` : "—"}
                  </div>
                  <div className="truncate" title={sysStatus.versions.engine?.type === "git" ? `${sysStatus.versions.engine.branch}-${sysStatus.versions.engine.hash}${sysStatus.versions.engine.dirty ? "*" : ""} (${sysStatus.versions.engine.date})` : sysStatus.versions.engine?.version_text || "unbekannt"}>
                    <strong>Engine:</strong> {sysStatus.versions.engine?.type === "git" ? `${sysStatus.versions.engine.hash}${sysStatus.versions.engine.dirty ? "*" : ""}` : (sysStatus.versions.engine?.version_text?.split(" ").pop() || "—")}
                  </div>
                  <div className="truncate" title={sysStatus.versions.hermes_ui ? `${sysStatus.versions.hermes_ui.branch}-${sysStatus.versions.hermes_ui.hash}${sysStatus.versions.hermes_ui.dirty ? "*" : ""} (${sysStatus.versions.hermes_ui.date})` : "nicht gefunden"}>
                    <strong>Hermes UI:</strong> {sysStatus.versions.hermes_ui ? `${sysStatus.versions.hermes_ui.hash}${sysStatus.versions.hermes_ui.dirty ? "*" : ""}` : "—"}
                  </div>
                  <div className="truncate" title={sysStatus.versions.hermes_agent ? `${sysStatus.versions.hermes_agent.branch}-${sysStatus.versions.hermes_agent.hash}${sysStatus.versions.hermes_agent.dirty ? "*" : ""} (${sysStatus.versions.hermes_agent.date})` : "nicht gefunden"}>
                    <strong>Hermes Agent:</strong> {sysStatus.versions.hermes_agent ? `${sysStatus.versions.hermes_agent.hash}${sysStatus.versions.hermes_agent.dirty ? "*" : ""}` : "—"}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </aside>

      {/* Main */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-14 shrink-0 items-center justify-between border-b border-border/40 px-6 bg-card/20 backdrop-blur-sm">
          <div className="text-xs font-medium text-muted-foreground tracking-wide uppercase font-sans">{active.hint}</div>
          <div className="flex items-center gap-2">
            <a
              href="https://git.tobisniceshomelab.ddnsfree.com/Hitonabi/mission-control-v2/src/branch/main/docs/BEDIENUNG.md"
              target="_blank"
              rel="noopener"
              className="flex h-8 items-center rounded-md border border-border/40 bg-background/40 px-2.5 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-all cursor-pointer font-semibold"
              title="Bedien-Anleitung"
            >
              Hilfe
            </a>

            <button
              onClick={() => {
                const ev = new KeyboardEvent("keydown", { key: "k", metaKey: true })
                document.dispatchEvent(ev)
              }}
              className="flex items-center gap-2 rounded-md border border-border/40 bg-background/40 px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground transition-all cursor-pointer"
            >
              <CommandIcon className="h-3.5 w-3.5" />
              <span>Suchen</span>
              <kbd className="rounded bg-muted px-1.5 py-0.5 font-mono text-[9px]">⌘K</kbd>
            </button>
          </div>
        </header>

        <main className="flex-1 overflow-y-auto p-6 scrollbar-thin">
          {view === "dashboard" && <DashboardView />}
          {view === "models" && <ModelsView />}
          {view === "connect" && <ConnectView />}
          {view === "memory" && <MemoryView />}
          {view === "agent" && <AgentView />}
          {view === "terminal" && <TerminalView />}
          {view === "guide" && <GuideView />}
          {!["dashboard", "models", "connect", "memory", "agent", "terminal", "guide"].includes(view) && (
            <Placeholder title={active.label} hint={active.hint} />
          )}
        </main>
      </div>
    </div>
  )
}

