import "server-only";
import type { ReactNode } from "react";
import { redirect } from "next/navigation";
import { toPreviewRole } from "@/features/auth/model";
import { dashboardGuardDestination } from "@/lib/auth/dashboard-policy";
import type { DashboardRoute } from "@/lib/auth/dashboard-routes";
import { getDashboardMenuRoutes } from "@/lib/auth/menu-access-server";
import { isMonetizationApiConfigured } from "@/lib/auth/server-config";
import { getServerSession } from "@/lib/auth/server-session";
import type { PreviewRole } from "@/lib/preview";
import { Button } from "@/components/ui/button";
import { DashboardPage } from "./dashboard-page";
import { firstDashboardDestination } from "./navigation";
import { DashboardRoutesProvider, PreviewLink } from "./preview-context";
import { RetryDashboardAccess } from "./retry-dashboard-access";

export function withDashboardAccess<Props>(
  route: DashboardRoute,
  render: (props: Props, role: PreviewRole) => ReactNode | Promise<ReactNode>,
) {
  return async function AuthorizedDashboardRoute(props: Props) {
    const configured = isMonetizationApiConfigured();
    const session = configured ? await getServerSession() : null;
    const authDestination = dashboardGuardDestination(configured, session);
    if (authDestination || !session) redirect(authDestination ?? "/signin");

    const role = toPreviewRole(session.role);
    const routes = await getDashboardMenuRoutes();
    if (routes?.includes(route)) {
      return (
        <DashboardRoutesProvider routes={routes}>
          {await render(props, role)}
        </DashboardRoutesProvider>
      );
    }

    const destination = routes && firstDashboardDestination(role, routes);
    if (route === "/" && destination) redirect(destination);

    const title = routes === null
      ? "Could not load menu permissions"
      : routes.length
        ? "Access denied"
        : "No pages available";
    const description = routes === null
      ? "Try again to load the pages available to your account."
      : routes.length
        ? "Your account does not have access to this page."
        : "Your account has no Monetization pages assigned.";

    return (
      <DashboardRoutesProvider routes={routes ?? []}>
        <DashboardPage role={role}>
          <section className="panel max-w-xl space-y-4 p-6 sm:p-8">
            <div className="space-y-2">
              <h1 className="text-xl font-semibold">{title}</h1>
              <p className="text-sm text-muted-foreground">{description}</p>
            </div>
            {routes === null ? (
              <RetryDashboardAccess />
            ) : destination && (
              <Button asChild>
                <PreviewLink href={destination}>Go to an available page</PreviewLink>
              </Button>
            )}
          </section>
        </DashboardPage>
      </DashboardRoutesProvider>
    );
  };
}
