import { Suspense } from "react";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { fetchAccessCustomers } from "@/app/customer/_lib/admin/access-server-api";
import {
  firstSearchParam,
  loadAdminPageContext,
  parseAdminListPageQuery,
} from "@/app/customer/_lib/admin/load-admin-page-context";
import {
  canManageMandateCustomers,
  canManageSection,
  pageKeysForSection,
} from "@/app/customer/_lib/admin/admin-section-permissions";
import { resolveClientPageCount } from "@/lib/list-pagination";

import { CustomersPageClient } from "./_components/customers-page-client";

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

export default async function CustomerAdminCustomersPage({
  params,
  searchParams,
}: Readonly<PageProps>) {
  const { tenant } = await params;
  // Model Portfolio (mandate) is a fully independent grant from Live customers (see Yii
  // CorporateCapability::MANDATE_CUSTOMERS_MANAGE) — an actor holding ONLY the mandate
  // checkbox must still reach this shared page. (2026-09-23)
  const ctx = await loadAdminPageContext(tenant, {
    page: pageKeysForSection("customers"),
    label: "Customers",
  });
  if (ctx.denied) {
    return ctx.deniedView;
  }

  const query = await searchParams;
  const { page, pageSize, q } = parseAdminListPageQuery(query, 20);
  const customerKind =
    firstSearchParam(query.customerKind).trim().toLowerCase() === "mandate"
      ? "mandate"
      : "live";
  const canManageCustomers =
    customerKind === "mandate"
      ? canManageMandateCustomers(ctx.capabilities)
      : canManageSection("customers", ctx.capabilities);
  const canViewMandateTab =
    canManageMandateCustomers(ctx.capabilities) ||
    Boolean(ctx.capabilities?.admin_assigned_customers);

  const result = await fetchAccessCustomers(tenant, { q, page, pageSize, customerKind });
  const data = result.data;
  const totalCount = data?.totalCount ?? data?.items?.length ?? 0;
  const resolvedPageSize = data?.pageSize ?? pageSize;
  const resolvedPage = data?.page ?? page;
  const pageCount = data?.pageCount ?? resolveClientPageCount(totalCount, resolvedPageSize);

  return (
    <CustomerPageShell>
      <Suspense fallback={null}>
        <CustomersPageClient
          tenant={tenant}
          initialCustomers={data?.items ?? []}
          groups={data?.groups ?? []}
          initialErrorMessage={result.errorMessage}
          initialQ={q}
          customerKind={customerKind}
          canManageCustomers={canManageCustomers}
          canViewMandateTab={canViewMandateTab}
          pagination={{
            page: resolvedPage,
            pageSize: resolvedPageSize,
            totalCount,
            pageCount,
          }}
        />
      </Suspense>
    </CustomerPageShell>
  );
}
