import NoAccess from "@/components/blocks/NoAccess/noAccess";
import type { RolePrivilegeType } from "@/lib/features/types";
import { AppShellSection, Box } from "@mantine/core";
import { IconSettings, IconUsersGroup } from "@tabler/icons-react";
import { Outlet } from "react-router";
import type { Route } from "../+types/root";
import PageHeader from "./shared/page.header";
import { ROUTES } from "@/lib/path";
import { checkAccess, FEATURE_SLUGS } from "@/lib/role-helpers";

export async function loader({ request, params }: Route.LoaderArgs) {
  const url = new URL(request.url);
  const pathname = url.pathname;

  let scopeType: RolePrivilegeType = "read";
  let featureSlug = FEATURE_SLUGS.userManagement;
  const { id } = params as { id: string };

  /*
   * The profile page is self-service and has no feature behind it.
   *
   * Everything under /admin/settings otherwise falls through to the
   * user-management check by default, so a user without that role was shown
   * NoAccess on their own profile.
   */
  if (pathname === ROUTES.profile.path) {
    return { pathname, hasAccess: true };
  }
  switch (pathname) {
    // user management
    case ROUTES.users.path:
      scopeType = "read";
      featureSlug = FEATURE_SLUGS.userManagement;
      break;
    case ROUTES.createUser.path:
      scopeType = "create";
      featureSlug = FEATURE_SLUGS.userManagement;
      break;
    case `${ROUTES.users.path}/${id}`:
      scopeType = "read";
      featureSlug = FEATURE_SLUGS.userManagement;
      break;

    // roles
    case ROUTES.roles.path:
      scopeType = "read";
      featureSlug = FEATURE_SLUGS.roleManagement;
      break;
    case ROUTES.createRoles.path:
      scopeType = "create";
      featureSlug = FEATURE_SLUGS.roleManagement;
      break;
    case `${ROUTES.roles.path}/${id}`:
      scopeType = "read";
      featureSlug = FEATURE_SLUGS.roleManagement;
      break;

    default:
      break;
  }

  const hasAccess = checkAccess(request, scopeType, featureSlug) ?? false;

  return { pathname, hasAccess };
}

const SettingsLayout: React.FC<Route.ComponentProps> = ({ loaderData }) => {
  const { pathname, hasAccess } = loaderData as unknown as {
    pathname: string;
    hasAccess: boolean;
  };
  return (
    <AppShellSection>
      {/* Profile is not part of the user/role tab pair. */}
      {[ROUTES.users.path, ROUTES.roles.path].includes(pathname) && (
        <PageHeader
          links={[
            {
              Icon: IconUsersGroup,
              label: "User Management",
              href: ROUTES.users.path,
            },
            {
              Icon: IconSettings,
              label: "Role Management",
              href: ROUTES.roles.path,
            },
          ]}
        />
      )}
      <Box py={20} px={28}>
        {hasAccess ? <Outlet /> : <NoAccess />}
      </Box>
    </AppShellSection>
  );
};

export default SettingsLayout;
