import { useState, useEffect } from "react";
import { Outlet, Link, useLocation } from "react-router-dom";
import { Terminal } from "../components/terminal/Terminal";
import { useWebSocket } from "../hooks/useWebSocket";
import { useTheme } from "../hooks/useTheme";

const NAV_ITEMS = [
  { path: "/", label: "Home" },
  { path: "/editor", label: "Editor" },
  { path: "/build", label: "Build" },
  { path: "/server", label: "Server" },
  { path: "/toolset", label: "Toolset" },
  { path: "/repos", label: "Repos" },
];

export function IDELayout({ sidebar }: { sidebar?: React.ReactNode }) {
  const [terminalOpen, setTerminalOpen] = useState(false);
  const [upstreamBehind, setUpstreamBehind] = useState(0);
  const location = useLocation();
  const { subscribe } = useWebSocket();
  const { theme, toggleTheme } = useTheme();

  useEffect(() => {
    return subscribe("git:upstream-update", (event) => {
      const data = event.data as { behind: number };
      if (data.behind > 0) {
        setUpstreamBehind((prev) => prev + data.behind);
      }
    });
  }, [subscribe]);

  useEffect(() => {
    if (location.pathname === "/repos") {
      setUpstreamBehind(0);
    }
  }, [location.pathname]);

  return (
    <div className="flex h-screen flex-col overflow-hidden" style={{ backgroundColor: "var(--forge-bg)" }}>
      <header
        className="flex shrink-0 items-center gap-6 px-4 py-2"
        style={{ borderBottom: "1px solid var(--forge-border)" }}
      >
        <h1
          className="text-lg font-bold"
          style={{
            fontFamily: "'Baskerville', 'Georgia', 'Palatino', serif",
            color: "var(--forge-accent)",
          }}
        >
          Layonara Forge
        </h1>
        <nav className="flex flex-1 items-center gap-1">
          {NAV_ITEMS.map((item) => {
            const isActive =
              item.path === "/" ? location.pathname === "/" : location.pathname.startsWith(item.path);
            return (
              <Link
                key={item.path}
                to={item.path}
                className="relative rounded px-2.5 py-1 text-sm transition-colors hover:bg-white/5"
                style={{
                  color: isActive ? "var(--forge-accent)" : "var(--forge-text-secondary)",
                  fontWeight: isActive ? 600 : 400,
                }}
              >
                {item.label}
                {item.path === "/repos" && upstreamBehind > 0 && (
                  <span className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-bold text-black">
                    {upstreamBehind}
                  </span>
                )}
              </Link>
            );
          })}
        </nav>
        <button
          onClick={toggleTheme}
          className="rounded px-2 py-1 text-sm transition-colors hover:bg-white/10"
          style={{ color: "var(--forge-text-secondary)" }}
          title={`Switch to ${theme === "dark" ? "light" : "dark"} mode`}
        >
          {theme === "dark" ? "\u2600\uFE0F" : "\uD83C\uDF19"}
        </button>
      </header>

      <div className="flex flex-1 flex-col overflow-hidden">
        <div className="flex flex-1 overflow-hidden">
          {sidebar && (
            <aside
              className="shrink-0 overflow-hidden"
              style={{
                width: "250px",
                borderRight: "1px solid var(--forge-border)",
              }}
            >
              {sidebar}
            </aside>
          )}
          <main className="flex-1 overflow-hidden">
            <Outlet />
          </main>
        </div>

        <button
          onClick={() => setTerminalOpen((v) => !v)}
          className="flex shrink-0 items-center gap-1 px-3 py-0.5 text-xs transition-colors hover:bg-white/5"
          style={{
            borderTop: "1px solid var(--forge-border)",
            color: "var(--forge-text-secondary)",
            fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
          }}
        >
          <span>{terminalOpen ? "\u25BC" : "\u25B2"}</span>
          <span>Terminal</span>
        </button>

        {terminalOpen && (
          <div
            className="shrink-0 overflow-hidden"
            style={{
              height: "300px",
              borderTop: "1px solid var(--forge-border)",
            }}
          >
            <Terminal sessionId="main" />
          </div>
        )}
      </div>
    </div>
  );
}
