import { Globe } from "lucide-react";

import { ListPageCard } from "@/app/dashboard/_components";
import { ErrorBanner } from "@/components/shared/error-banner";
import { fetchBackendCustomers } from "@/app/dashboard/customers/_lib/customers-list-api";

import { PortalSectionShell } from "../_components/portal-section-shell";
import { PortalRolesPageClient } from "../_components/portal-roles-page-client";
import {
  fetchPortalEntitlements,
  fetchPortalGroups,
  fetchPortalRouteCatalog,
  parseCustomerIdFromQuery,
} from "../_lib/portal-access-server-api";

type PageProps = {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

export default async function PortalRolesPage({ searchParams }: PageProps) {
  const query = await searchParams;
  const customerId = parseCustomerIdFromQuery(query);

  const customersResult = await fetchBackendCustomers({ page: 1, pageSize: 200 });
  const resolvedCustomerId = customerId ?? customersResult.rows[0]?.id ?? null;

  const [groupsResult, catalogResult, entitlementsResult] =
    resolvedCustomerId != null
      ? await Promise.all([
          fetchPortalGroups(resolvedCustomerId),
          fetchPortalRouteCatalog(),
          fetchPortalEntitlements(resolvedCustomerId),
        ])
      : [
          { items: [], errorMessage: null },
          { apps: [], errorMessage: null },
          { data: null, errorMessage: null },
        ];

  return (
    <ListPageCard
      icon={Globe}
      title="Portal roles"
      description="Tenant roles (route sets) assigned to portal users."
      breadcrumb={[
        { label: "Admins & Access", href: "/dashboard/admins" },
        { label: "Portal ACL" },
        { label: "Roles" },
      ]}
    >
      <PortalSectionShell
        customers={customersResult.rows}
        selectedCustomerId={resolvedCustomerId}
      >
        <ErrorBanner message={customersResult.errorMessage ?? groupsResult.errorMessage} className="mb-4" />
        {!resolvedCustomerId ? (
          <p className="text-muted-foreground text-sm">Select a customer to manage portal roles.</p>
        ) : (
          <PortalRolesPageClient
            customerId={resolvedCustomerId}
            initialGroups={groupsResult.items}
            appCatalog={catalogResult.apps}
            entitledRoutes={entitlementsResult.data?.entitled_routes ?? []}
            initialErrorMessage={catalogResult.errorMessage ?? entitlementsResult.errorMessage}
          />
        )}
      </PortalSectionShell>
    </ListPageCard>
  );
}
