import { ShieldCheck } from "lucide-react";

import { ListPageCard } from "@/app/dashboard/_components";
import { fetchBackendRbacModules } from "@/app/dashboard/admins/access/app-modules/_lib/app-modules-server-api";
import { fetchBackendRole } from "../_lib/roles-server-api";
import { EditRolePageClient } from "./_components/edit-role-page-client";

type PageProps = {
  params: Promise<{
    roleId: string;
  }>;
};

export default async function EditRolePage({ params }: PageProps) {
  const { roleId: rawRoleId } = await params;
  const roleId = decodeURIComponent(rawRoleId);
  const [
    { role, errorMessage },
    { modules, errorMessage: modulesErrorMessage },
  ] = await Promise.all([fetchBackendRole(roleId), fetchBackendRbacModules()]);

  if (!role) {
    return (
      <ListPageCard
        icon={ShieldCheck}
        title="Role not found"
        breadcrumb={[
          { label: "Roles", href: "/dashboard/admins/access/roles" },
          { label: roleId },
        ]}
      >
        <p className="text-muted-foreground text-sm">
          {errorMessage ?? "The requested role does not exist."}
        </p>
      </ListPageCard>
    );
  }

  return (
    <ListPageCard
      icon={ShieldCheck}
      title={`Edit role: ${role.name}`}
      breadcrumb={[
        { label: "Admins & Access", href: "/dashboard/admins/users" },
        { label: "Roles", href: "/dashboard/admins/access/roles" },
        { label: role.name },
      ]}
    >
      <EditRolePageClient
        role={role}
        availableModules={modules}
        modulesErrorMessage={modulesErrorMessage}
      />
    </ListPageCard>
  );
}
