"use client";

// The admin + organizer app shell: a themed left sidebar (icon nav, grouped,
// active-route highlight), a top bar, a mobile drawer, and a light/dark toggle.
// Nav configs live here (not in the server layouts) because Lucide icon
// components aren't serializable across the server→client boundary.

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  CalendarDays,
  Tags,
  Images,
  ImagePlus,
  Wallet,
  Banknote,
  Undo2,
  CalendarX2,
  Users,
  Ticket,
  Share2,
  ShoppingBag,
  Store,
  Layers,
  Megaphone,
  HandCoins,
  BarChart3,
  ScrollText,
  Settings,
  QrCode,
  Receipt,
  Sun,
  Moon,
  Menu,
  X,
  LogOut,
  type LucideIcon,
} from "lucide-react";
import { signOut as authSignOut } from "next-auth/react";
import BrandLogo from "@/components/brand-logo";

type Theme = "dark" | "light";
type NavItem = { href: string; label: string; icon: LucideIcon };
type NavGroup = { heading?: string; items: NavItem[] };

const ADMIN_NAV: NavGroup[] = [
  { items: [{ href: "/admin", label: "Overview", icon: LayoutDashboard }] },
  {
    heading: "Catalog",
    items: [
      { href: "/admin/events", label: "Events", icon: CalendarDays },
      { href: "/admin/categories", label: "Categories", icon: Tags },
      { href: "/admin/gallery", label: "Gallery", icon: Images },
      { href: "/admin/gallery/submissions", label: "Submissions", icon: ImagePlus },
    ],
  },
  {
    heading: "Money",
    items: [
      { href: "/admin/earnings", label: "Earnings", icon: Wallet },
      { href: "/admin/payouts", label: "Payouts", icon: Banknote },
      { href: "/admin/refunds", label: "Refunds", icon: Undo2 },
      { href: "/admin/cancellations", label: "Cancellations", icon: CalendarX2 },
      { href: "/admin/financing", label: "Financing", icon: HandCoins },
    ],
  },
  {
    heading: "People",
    items: [
      { href: "/admin/organizers", label: "Organizers", icon: Users },
      { href: "/admin/orders", label: "Orders & buyers", icon: Receipt },
      { href: "/admin/merch-shops", label: "Merch shops", icon: Store },
      { href: "/admin/merch-orders", label: "Merch orders", icon: ShoppingBag },
    ],
  },
  {
    heading: "System",
    items: [
      { href: "/admin/reports", label: "Reports", icon: BarChart3 },
      { href: "/admin/audit", label: "Audit log", icon: ScrollText },
      { href: "/admin/settings", label: "Settings", icon: Settings },
    ],
  },
];

const ORGANIZER_NAV: NavGroup[] = [
  {
    items: [
      { href: "/dashboard", label: "Events", icon: CalendarDays },
      { href: "/dashboard/checkin", label: "Check-in", icon: QrCode },
      { href: "/dashboard/customers", label: "Customers", icon: Users },
      { href: "/dashboard/segments", label: "Segments", icon: Layers },
      { href: "/dashboard/campaigns", label: "Campaigns", icon: Megaphone },
      { href: "/dashboard/coupons", label: "Coupons", icon: Ticket },
      { href: "/dashboard/affiliates", label: "Affiliates", icon: Share2 },
      { href: "/dashboard/merch", label: "Merch", icon: ShoppingBag },
      { href: "/dashboard/earnings", label: "Earnings", icon: Wallet },
      { href: "/dashboard/financing", label: "Financing", icon: HandCoins },
    ],
  },
];

const ROOTS = new Set(["/admin", "/dashboard"]);

// Highlight exactly one item: the longest href that the current path is under.
function activeHref(pathname: string, groups: NavGroup[]): string | null {
  let best: string | null = null;
  for (const g of groups) {
    for (const it of g.items) {
      const matches = ROOTS.has(it.href)
        ? pathname === it.href
        : pathname === it.href || pathname.startsWith(it.href + "/");
      if (matches && (best === null || it.href.length > best.length)) best = it.href;
    }
  }
  return best;
}

export default function BackendShell({
  role,
  userEmail,
  initialTheme,
  children,
}: {
  role: "admin" | "organizer";
  userEmail: string;
  initialTheme: Theme;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const [theme, setTheme] = useState<Theme>(initialTheme);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const groups = role === "admin" ? ADMIN_NAV : ORGANIZER_NAV;
  const active = activeHref(pathname, groups);
  const homeHref = role === "admin" ? "/admin" : "/dashboard";

  function toggleTheme() {
    const next: Theme = theme === "dark" ? "light" : "dark";
    setTheme(next);
    // Persist for the next server render so there's no flash of the wrong theme.
    document.cookie = `be-theme=${next}; path=/; max-age=31536000; samesite=lax`;
  }

  function signOut() {
    void authSignOut({ callbackUrl: "/login" });
  }

  const sidebar = (
    <div className="flex h-full flex-col">
      {/* Brand */}
      <Link
        href={homeHref}
        className="flex h-16 items-center gap-2 px-5"
        onClick={() => setDrawerOpen(false)}
      >
        <BrandLogo size="sm" showTagline wordClassName="text-be-text" accentClassName="text-brand-green" />
        <span className="text-xs font-medium text-be-muted">
          {role === "admin" ? "Admin" : "Studio"}
        </span>
      </Link>

      {/* Nav */}
      <nav className="flex-1 space-y-5 overflow-y-auto px-3 py-2">
        {groups.map((group, gi) => (
          <div key={group.heading ?? gi}>
            {group.heading && (
              <p className="px-3 pb-1.5 text-[0.65rem] font-semibold uppercase tracking-wider text-be-muted/70">
                {group.heading}
              </p>
            )}
            <ul className="space-y-0.5">
              {group.items.map((it) => {
                const isActive = it.href === active;
                const Icon = it.icon;
                return (
                  <li key={it.href}>
                    <Link
                      href={it.href}
                      onClick={() => setDrawerOpen(false)}
                      aria-current={isActive ? "page" : undefined}
                      className={`group flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                        isActive
                          ? "bg-brand-green-wash text-brand-green-h"
                          : "text-be-muted hover:bg-be-surface-2 hover:text-be-text"
                      }`}
                    >
                      <Icon className={`h-[18px] w-[18px] ${isActive ? "" : "opacity-80"}`} />
                      {it.label}
                    </Link>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </nav>

      {/* User footer */}
      <div className="border-t border-be-border p-3">
        <div className="truncate px-2 pb-2 text-xs text-be-muted" title={userEmail}>
          {userEmail}
        </div>
        <button
          onClick={signOut}
          className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-be-muted transition-colors hover:bg-be-surface-2 hover:text-be-text"
        >
          <LogOut className="h-4 w-4" />
          Sign out
        </button>
      </div>
    </div>
  );

  return (
    <div data-theme={theme} className="be-root flex min-h-screen">
      {/* Desktop sidebar */}
      <aside className="hidden w-60 shrink-0 border-r border-be-border bg-be-surface lg:block">
        <div className="sticky top-0 h-screen">{sidebar}</div>
      </aside>

      {/* Mobile drawer */}
      {drawerOpen && (
        <div className="fixed inset-0 z-40 lg:hidden">
          <div
            className="absolute inset-0 bg-black/50"
            onClick={() => setDrawerOpen(false)}
            aria-hidden="true"
          />
          <aside className="absolute inset-y-0 left-0 w-64 border-r border-be-border bg-be-surface shadow-xl">
            {sidebar}
          </aside>
        </div>
      )}

      {/* Main column */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="sticky top-0 z-30 flex h-16 items-center justify-between gap-3 border-b border-be-border bg-be-surface/80 px-4 backdrop-blur sm:px-6">
          <div className="flex items-center gap-2">
            <button
              onClick={() => setDrawerOpen(true)}
              className="grid h-9 w-9 place-items-center rounded-lg text-be-muted hover:bg-be-surface-2 hover:text-be-text lg:hidden"
              aria-label="Open navigation"
            >
              <Menu className="h-5 w-5" />
            </button>
            <span className="pill pill-ok hidden sm:inline-flex">
              {role === "admin" ? "Platform staff" : "Organizer"}
            </span>
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={toggleTheme}
              className="grid h-9 w-9 place-items-center rounded-lg text-be-muted transition-colors hover:bg-be-surface-2 hover:text-be-text"
              aria-label={`Switch to ${theme === "dark" ? "light" : "dark"} theme`}
              title={`Switch to ${theme === "dark" ? "light" : "dark"} theme`}
            >
              {theme === "dark" ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
            </button>
          </div>
        </header>

        <main className="mx-auto w-full max-w-6xl flex-1 px-4 py-8 sm:px-6 lg:px-8">
          {children}
        </main>
      </div>

      {/* Close button rendered inside drawer for reachability on small screens */}
      {drawerOpen && (
        <button
          onClick={() => setDrawerOpen(false)}
          className="fixed left-[16.5rem] top-4 z-50 grid h-9 w-9 place-items-center rounded-lg bg-be-surface text-be-text shadow lg:hidden"
          aria-label="Close navigation"
        >
          <X className="h-5 w-5" />
        </button>
      )}
    </div>
  );
}
