import "server-only";
import type { ReactNode } from "react";
import { redirect } from "next/navigation";
import { DashboardAccessRetry } from "@/components/layout/dashboard-access-retry";
import { DashboardMenuProvider } from "@/components/layout/dashboard-menu-context";
import { DashboardShell } from "@/components/layout/dashboard-shell";
import { firstDashboardDestination } from "@/components/layout/navigation";
import { SessionMonitor } from "@/features/auth/session-lifecycle";
import type { SafeAuthSession } from "@/features/auth/auth-client";
import type { DashboardRoute } from "./dashboard-menus";
import { getDashboardMenuRoutes } from "./menu-access-server";
import { isCsmsApiConfigured } from "./server-config";
import { getServerSession } from "./server-session";

export function withDashboardAccess<Props>(
  route: DashboardRoute,
  render: (props: Props, session: SafeAuthSession | null) => ReactNode | Promise<ReactNode>,
) {
  return async function AuthorizedDashboardPage(props: Props) {
    const connected = isCsmsApiConfigured();
    if (!connected && process.env.NODE_ENV === "production") redirect("/signin");
    const session = connected ? await getServerSession() : null;
    if (connected && !session) redirect("/signin");
    if (session?.passwordSetupRequired) redirect("/set-password");

    const routes = connected ? await getDashboardMenuRoutes() : null;
    let content: ReactNode;
    if (!connected || routes?.includes(route)) {
      content = await render(props, session);
    } else {
      const destination = routes && firstDashboardDestination(routes);
      if (route === "/" && destination) redirect(destination);
      content = (
        <section className="panel max-w-xl space-y-4 p-6">
          <h1 className="text-xl font-semibold">
            {routes === null ? "Could not load menu permissions" : routes.length ? "Access denied" : "No pages available"}
          </h1>
          {routes === null ? (
            <>
              <p className="text-sm text-muted-foreground">Try again to load the pages available to your account.</p>
              <DashboardAccessRetry />
            </>
          ) : (
            <>
              <p className="text-sm text-muted-foreground">
                {routes.length ? "Your account does not have access to this page." : "Your account has no CSMS pages assigned."}
              </p>
              {destination && <a href={destination} className="text-primary underline">Go to an available page</a>}
            </>
          )}
        </section>
      );
    }

    return (
      <DashboardMenuProvider routes={connected ? routes ?? [] : null}>
        <DashboardShell session={session}>
          {session && <SessionMonitor session={session} />}
          {content}
        </DashboardShell>
      </DashboardMenuProvider>
    );
  };
}
