import { Suspense } from "react";

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

import { LinkBankAccountsPageClient } from "./_components/link-bank-accounts-page-client";

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

export default async function LinkBankAccountsAdminPage({
  params,
  searchParams,
}: Readonly<PageProps>) {
  const { tenant } = await params;
  const ctx = await loadAdminPageContext(tenant, {
    page: pageKeysForSection("linkBankAccounts"),
    label: "Link Bank Accounts",
  });
  if (ctx.denied) {
    return ctx.deniedView;
  }

  const query = await searchParams;
  const { page, pageSize, q } = parseAdminListPageQuery(query, 20);

  const result = await fetchPortalLinkBankCustomers(tenant, { search: q, page, pageSize });
  const canManage = canManageSection("linkBankAccounts", ctx.capabilities);

  const totalCount = result.totalCount ?? result.items.length;
  const resolvedPageSize = result.pageSize ?? pageSize;
  const resolvedPage = result.page ?? page;
  const pageCount = result.pageCount ?? resolveClientPageCount(totalCount, resolvedPageSize);

  return (
    <CustomerPageShell>
      <Suspense fallback={null}>
        <LinkBankAccountsPageClient
          tenant={tenant}
          initialCustomers={result.items}
          initialErrorMessage={result.errorMessage}
          canManage={canManage}
          capabilities={ctx.capabilities}
          initialQ={q}
          pagination={{
            page: resolvedPage,
            pageSize: resolvedPageSize,
            totalCount,
            pageCount,
          }}
        />
      </Suspense>
    </CustomerPageShell>
  );
}
