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 { PortalUsersPageClient } from "../_components/portal-users-page-client";
import { fetchPortalUsers, parseCustomerIdFromQuery } from "../_lib/portal-access-server-api";

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

export default async function PortalUsersPage({ 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 usersResult =
    resolvedCustomerId != null
      ? await fetchPortalUsers(resolvedCustomerId)
      : { items: [], groups: [], errorMessage: null };

  return (
    <ListPageCard
      icon={Globe}
      title="Portal users"
      description="Customer portal logins and role assignments."
      breadcrumb={[
        { label: "Admins & Access", href: "/dashboard/admins" },
        { label: "Portal ACL" },
        { label: "Users" },
      ]}
    >
      <PortalSectionShell
        customers={customersResult.rows}
        selectedCustomerId={resolvedCustomerId}
      >
        <ErrorBanner message={customersResult.errorMessage ?? usersResult.errorMessage} className="mb-4" />
        {!resolvedCustomerId ? (
          <p className="text-muted-foreground text-sm">Select a customer to manage portal users.</p>
        ) : (
          <PortalUsersPageClient
            customerId={resolvedCustomerId}
            initialUsers={usersResult.items}
            groups={usersResult.groups}
            initialErrorMessage={usersResult.errorMessage}
          />
        )}
      </PortalSectionShell>
    </ListPageCard>
  );
}
