import { redirect, type LoaderFunctionArgs } from "react-router";
import { useRoleAccess } from "@/hooks/useRoleAccess";
import { listDashboards } from "@/lib/features/dashboard/action";
import type { DashboardListItem } from "@/lib/features/dashboard/types";
import { checkAccess, getFirstAccessibleRoute } from "@/lib/role-helpers";
import DashboardClientPage from "./_client";

/**
 * NOTE: this page deliberately does NOT use createRoleProtectedLoader.
 *
 * That helper redirects to /admin/dashboard when access is missing — which is
 * this route, so it would loop. /admin/dashboard is also the fallback landing
 * route for users with no other module access, so it must never hard-403: a
 * viewer with nothing shared gets a friendly empty state instead.
 */
export async function loader({ request }: LoaderFunctionArgs) {
  const canRead = checkAccess(request, "read", "dashboard");

  // Preserved from the original stub: users without dashboard access are sent
  // to the first module they can actually see. Only when there is nowhere else
  // to go do they stay here and get the empty state.
  if (!canRead) {
    const fallback = getFirstAccessibleRoute(request);
    if (fallback && fallback !== "/admin/dashboard") {
      return redirect(fallback);
    }
  }

  // "Dashboard admin" on the frontend = create-or-update on the feature, the
  // same predicate the backend uses. Presentation only; the server re-checks.
  const isDashboardAdmin =
    checkAccess(request, "create", "dashboard") ||
    checkAccess(request, "update", "dashboard");

  // A viewer with no read privilege would be refused by the backend guard, so
  // skip the call entirely and let the empty state speak.
  let dashboards: DashboardListItem[] = [];
  if (canRead) {
    const response = await listDashboards({
      Cookie: request.headers.get("Cookie") ?? "",
    });
    // A failed list is treated as "nothing to show", never a page error — this
    // route is a landing target and must always render something friendly.
    dashboards = response?.success ? (response.data ?? []) : [];
  }

  return { dashboards, canRead, isDashboardAdmin };
}

const DashboardPage = ({
  loaderData,
}: {
  loaderData: {
    dashboards: DashboardListItem[];
    canRead: boolean;
    isDashboardAdmin: boolean;
  };
}) => {
  const { dashboards, canRead, isDashboardAdmin } = loaderData;
  const { checkClientAccess } = useRoleAccess();

  // Re-derived client-side so the affordance stays correct after a client
  // navigation; the loader value is the SSR-correct default.
  const clientAdmin =
    checkClientAccess("create", "dashboard") ||
    checkClientAccess("update", "dashboard");

  return (
    <DashboardClientPage
      dashboards={dashboards}
      canRead={canRead}
      isDashboardAdmin={isDashboardAdmin || clientAdmin}
    />
  );
};

export default DashboardPage;
