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 { PortalEntitlementsForm } from "../_components/portal-entitlements-form";
import {
  fetchPortalEntitlements,
  parseCustomerIdFromQuery,
} from "../_lib/portal-access-server-api";

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

export default async function PortalEntitlementsPage({ 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 entitlementsResult =
    resolvedCustomerId != null
      ? await fetchPortalEntitlements(resolvedCustomerId)
      : { data: null, errorMessage: null };

  return (
    <ListPageCard
      icon={Globe}
      title="Portal entitlements"
      description="Assign customer portal apps and routes (tenant ceiling)."
      breadcrumb={[
        { label: "Admins & Access", href: "/dashboard/admins" },
        { label: "Portal ACL" },
        { label: "Entitlements" },
      ]}
    >
      <PortalSectionShell
        customers={customersResult.rows}
        selectedCustomerId={resolvedCustomerId}
      >
        <ErrorBanner message={customersResult.errorMessage} className="mb-4" />
        {!resolvedCustomerId ? (
          <p className="text-muted-foreground text-sm">Select a customer to manage entitlements.</p>
        ) : (
          <PortalEntitlementsForm
            customerId={resolvedCustomerId}
            customerName={entitlementsResult.data?.customer_name}
            apps={entitlementsResult.data?.apps ?? []}
            initialRoutes={entitlementsResult.data?.entitled_routes ?? []}
            hasConfiguredEntitlements={entitlementsResult.data?.has_configured_entitlements ?? false}
            initialErrorMessage={entitlementsResult.errorMessage}
          />
        )}
      </PortalSectionShell>
    </ListPageCard>
  );
}
