import AdminSidebar from "@/components/admin/AdminSidebar";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import { listBrandsForAdmin } from "@/actions/brands";
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import "@/styles/admin-design-system.css";
import { ToastProvider } from "@/components/admin/Toast";
import { ToastContainer } from "@/components/admin/ToastContainer";
import { SmoothViewTransition } from "@/components/transitions/SmoothViewTransition";
import { RouteAnnouncer } from "@/components/transitions/RouteAnnouncer";
import CommandPalette from "@/components/admin/CommandPalette";
import PWAInstallPrompt from "@/components/pwa/InstallPrompt";
import { getEnabledAddons } from "@/actions/billing/stripe-portal";

export const dynamic = "force-dynamic";

function ToastProviderWrapper({ children }: { children: React.ReactNode }) {
  return (
    <ToastProvider>
      {children}
      <ToastContainer />
    </ToastProvider>
  );
}

export default async function AdminLayout({ children }: { children: React.ReactNode }) {
  let adminUser = null;
  let authError: string | null = null;

  try {
    adminUser = await getAdminUser();
  } catch (error) {
    console.error("Admin auth error:", error);
    authError = "Failed to verify authentication. Please try again.";
  }

  if (authError) {
    return (
      <ToastProviderWrapper>
        <AdminSidebar userRole={null} />
        <div className="min-h-screen lg:pl-60 admin-section" style={{ backgroundColor: "var(--admin-bg)" }}>
          <AdminAccessDenied message={authError} />
        </div>
      </ToastProviderWrapper>
    );
  }

  if (!adminUser) {
    let attemptedEmail: string | null = null;
    try {
      const { data: session } = await getSession();
      attemptedEmail = session?.user?.email ?? null;
    } catch {}
    const message = attemptedEmail
      ? `Your account (${attemptedEmail}) does not have admin access.`
      : "Your account does not have admin access.";
    return (
      <ToastProviderWrapper>
        <AdminSidebar userRole={null} />
        <div className="min-h-screen lg:pl-60 admin-section" style={{ backgroundColor: "var(--admin-bg)" }}>
          <AdminAccessDenied message={message} />
        </div>
      </ToastProviderWrapper>
    );
  }

  if (adminUser.must_change_password) {
    redirect("/change-password");
  }

  let activeBrandId: string | null = null;
  try {
    activeBrandId = await getActiveBrandId(adminUser);
  } catch (err) {
    console.error("[admin/layout] getActiveBrandId failed:", err);
  }

  let brands: Awaited<ReturnType<typeof listBrandsForAdmin>> = [];
  try {
    brands = await listBrandsForAdmin();
  } catch (err) {
    console.error("[admin/layout] listBrandsForAdmin failed:", err);
  }

  let enabledAddons: Record<string, boolean> = {};
  if (activeBrandId) {
    try {
      enabledAddons = await getEnabledAddons(activeBrandId);
    } catch (err) {
      console.error("[admin/layout] getEnabledAddons failed:", err);
    }
  }

  return (
    <ToastProviderWrapper>
      <AdminSidebar
        userRole={adminUser.role}
        brandIds={adminUser.brand_ids}
        activeBrandId={activeBrandId}
        brands={brands}
        enabledAddons={enabledAddons}
      />
      <CommandPalette />
      <div
        id="page-content"
        className="min-h-screen lg:pl-60 admin-section outline-none"
        style={{ backgroundColor: "var(--admin-bg)" }}
      >
        <SmoothViewTransition>{children}</SmoothViewTransition>
        <RouteAnnouncer />
      </div>
      <PWAInstallPrompt />
    </ToastProviderWrapper>
  );
}
