import Link from "next/link";
import { Plus, Wrench } from "lucide-react";
import { requireAuth } from "@/lib/auth/guards";
import { getEffectivePlan } from "@/lib/billing/subscription";
import { getActiveBranding, hexToHslTriplet } from "@/lib/branding";
import { isFlagEnabled } from "@/lib/flags";
import { SidebarNav } from "@/components/app/sidebar-nav";
import { AppMobileNav } from "@/components/app/app-mobile-nav";
import { UserMenu } from "@/components/app/user-menu";
import { CommandPalette } from "@/components/app/command-palette";
import { ImpersonationBanner } from "@/components/app/impersonation-banner";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { Button } from "@/components/ui/button";
import { Logo } from "@/components/ui/logo";

// Authed, DB-backed dashboard — never statically prerender.
export const dynamic = "force-dynamic";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const session = await requireAuth();
  const activeOrgId = session.session.activeOrganizationId;
  const [{ key: plan }, branding, maintenance] = await Promise.all([
    getEffectivePlan(session.user.id, activeOrgId),
    getActiveBranding(session.user.id, activeOrgId),
    isFlagEnabled("maintenance_banner"),
  ]);
  const isAdmin = session.user.role === "admin";

  // White-label: override the brand accent with the org's primary color so the
  // whole app shell (logo tile, active nav, buttons) adopts it.
  const brandHsl = hexToHslTriplet(branding?.primaryColor);
  const brandStyle = brandHsl
    ? ({ "--brand": brandHsl, "--ring": brandHsl } as React.CSSProperties)
    : undefined;
  const workspaceName = branding?.brandName ?? "Podcast Distribution AI";

  return (
    <ThemeProvider>
      <div className="flex min-h-screen flex-col" style={brandStyle}>
        <ImpersonationBanner />
        {maintenance && (
          <div className="flex items-center justify-center gap-2 bg-warning px-4 py-2 text-center text-sm font-medium text-warning-foreground">
            <Wrench className="h-4 w-4" />
            We&apos;re performing scheduled maintenance — some features may be briefly unavailable.
          </div>
        )}

        <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-border bg-background/85 px-4 backdrop-blur-md md:px-6">
          <div className="flex items-center gap-1">
            <AppMobileNav plan={plan} workspaceName={workspaceName} />
            <Link href="/dashboard" className="flex items-center" aria-label={workspaceName}>
              {branding?.logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={branding.logoUrl}
                  alt={workspaceName}
                  className="h-8 w-auto max-w-[160px] object-contain"
                />
              ) : (
                <Logo className="h-7 w-auto" priority />
              )}
            </Link>
          </div>
          <div className="flex items-center gap-3">
            <Button asChild size="sm">
              <Link href="/episodes/new">
                <Plus className="h-4 w-4" /> New episode
              </Link>
            </Button>
            <UserMenu
              name={session.user.name}
              email={session.user.email}
              image={session.user.image}
              isAdmin={isAdmin}
            />
          </div>
        </header>

        <div className="flex flex-1">
          <aside className="hidden w-64 shrink-0 border-r border-border bg-background md:block">
            <div className="sticky top-16">
              <SidebarNav plan={plan} />
            </div>
          </aside>
          <main className="flex-1 bg-secondary/50">
            <div className="container max-w-6xl py-8 md:py-10">{children}</div>
            {branding && !branding.removePoweredBy && (
              <p className="pb-8 text-center text-xs text-muted-foreground">Powered by Podcast Distribution AI</p>
            )}
          </main>
        </div>

        <CommandPalette />
      </div>
    </ThemeProvider>
  );
}
