import { useEffect, useMemo, useState } from "react";
import { NavLink, Outlet, useLocation } from "react-router-dom";

const QUALITY_SUB_ITEMS = [
  { to: "/quality/dashboard", title: "Overview" },
  { to: "/quality/pr-list", title: "PR List" },
  { to: "/quality/settings", title: "Settings" },
] as const;

const PAGE_TITLES: Record<string, string> = {
  "/planning": "Strategic Planning Workspace",
  "/devops": "Delivery Execution Workspace",
  "/quality/dashboard": "Quality Gate Overview",
  "/quality/pr-list": "Quality Gate · PR List",
  "/quality/settings": "Quality Gate · Settings",
};

export default function Layout() {
  const { pathname } = useLocation();
  const inQuality = pathname.startsWith("/quality");
  const [qualityExpanded, setQualityExpanded] = useState<boolean>(inQuality);

  useEffect(() => {
    if (inQuality) {
      setQualityExpanded(true);
    }
  }, [inQuality]);

  const pageTitle = useMemo(() => {
    if (PAGE_TITLES[pathname]) {
      return PAGE_TITLES[pathname];
    }
    if (inQuality) {
      return "Quality Gate";
    }
    return "SAFe OS";
  }, [pathname, inQuality]);

  return (
    <div className="flex h-screen w-screen bg-[#fafafa]">
      {/* ─── Sidebar ─── */}
      <nav className="w-[280px] shrink-0 bg-surface-dark text-txt-inverse flex flex-col py-8 border-r border-white/10">
        <div className="px-8 mb-9 text-2xl font-extrabold tracking-tight select-none">
          SAFe <span className="text-magenta">OS</span>
        </div>

        <div className="px-8 text-[11px] text-gray-500 uppercase font-bold tracking-widest mb-4">
          Agent Pipeline
        </div>

        <NavLink
          to="/planning"
          className={({ isActive }) =>
            `mx-4 rounded-xl flex items-center gap-3 px-4 py-3 border border-transparent transition-all cursor-pointer ${
              isActive
                ? "border-magenta/40 bg-white/10"
                : "hover:bg-white/5"
            }`
          }
        >
          {({ isActive }) => (
            <>
              <span
                className={`w-2 h-2 rounded-full shrink-0 ${
                  isActive ? "bg-magenta" : "bg-gray-600"
                }`}
              />
              <div>
                <div className="font-bold text-[0.95rem]">1. Planning Council Agent</div>
                <div className="text-xs text-gray-400">Business and architecture planning</div>
              </div>
            </>
          )}
        </NavLink>

        <NavLink
          to="/devops"
          className={({ isActive }) =>
            `mx-4 rounded-xl flex items-center gap-3 px-4 py-3 border border-transparent transition-all cursor-pointer ${
              isActive
                ? "border-magenta/40 bg-white/10"
                : "hover:bg-white/5"
            }`
          }
        >
          {({ isActive }) => (
            <>
              <span
                className={`w-2 h-2 rounded-full shrink-0 ${
                  isActive ? "bg-magenta" : "bg-gray-600"
                }`}
              />
              <div>
                <div className="font-bold text-[0.95rem]">2. DevOps Agent</div>
                <div className="text-xs text-gray-400">Story breakdown and implementation</div>
              </div>
            </>
          )}
        </NavLink>

        <div className="mx-4 rounded-xl border border-transparent">
          <button
            type="button"
            onClick={() => setQualityExpanded((v) => !v)}
            className={`w-full rounded-xl flex items-center gap-3 px-4 py-3 transition-all text-left ${
              inQuality ? "bg-white/10 border border-magenta/40" : "hover:bg-white/5"
            }`}
          >
            <span
              className={`w-2 h-2 rounded-full shrink-0 ${
                inQuality ? "bg-magenta" : "bg-gray-600"
              }`}
            />
            <div className="min-w-0 flex-1">
              <div className="font-bold text-[0.95rem]">3. Quality Gate Agent</div>
              <div className="text-xs text-gray-400">Automated validation and review</div>
            </div>
            <span className={`text-xs text-gray-400 transition-transform ${qualityExpanded ? "rotate-90" : ""}`}>
              ▶
            </span>
          </button>

          {qualityExpanded && (
            <div className="pl-10 pr-3 pb-3 pt-1 flex flex-col gap-1">
              {QUALITY_SUB_ITEMS.map((sub) => (
                <NavLink
                  key={sub.to}
                  to={sub.to}
                  className={({ isActive }) =>
                    `text-xs font-bold px-3 py-2 rounded-lg transition-colors ${
                      isActive
                        ? "text-magenta bg-white/10"
                        : "text-gray-400 hover:text-white hover:bg-white/5"
                    }`
                  }
                >
                  {sub.title}
                </NavLink>
              ))}
            </div>
          )}
        </div>

        <div className="mt-auto px-8 text-[0.7rem] text-gray-600">
          T-Systems · SAFe Multi-Agent Demo UI
        </div>
      </nav>

      {/* ─── Main workspace ─── */}
      <main className="flex-1 flex flex-col bg-white min-w-0">
        <header className="h-20 px-10 flex items-center justify-between border-b border-border/80 bg-white/90 backdrop-blur shrink-0">
          <h1 className="text-2xl font-extrabold tracking-tight">{pageTitle}</h1>
        </header>

        <div className="flex-1 overflow-hidden">
          <Outlet />
        </div>
      </main>
    </div>
  );
}
