import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import {
  canManageSection,
  canViewSection,
  pageKeysForSection,
} from "@/app/customer/_lib/admin/admin-section-permissions";
import { loadAdminPageContext } from "@/app/customer/_lib/admin/load-admin-page-context";
import { fetchPortalLinkBankCustomers } from "@/app/customer/_lib/admin/link-bank-accounts-server-api";
import { fetchPortalUnassignedBanks } from "@/app/customer/_lib/admin/parent-banks-server-api";

import { UnassignedBanksPageClient } from "./_components/unassigned-banks-page-client";

type PageProps = {
  params: Promise<{ tenant: string }>;
};

export default async function UnassignedBanksAdminPage({ params }: Readonly<PageProps>) {
  const { tenant } = await params;
  const ctx = await loadAdminPageContext(tenant, {
    page: pageKeysForSection("unassignedBanks"),
    label: "Unassigned Banks",
  });
  if (ctx.denied) {
    return ctx.deniedView;
  }

  const capabilities = ctx.capabilities;
  const canViewLinkCustomers = canViewSection("linkBankAccounts", capabilities);
  const canManage = canManageSection("unassignedBanks", capabilities);

  const [unassignedResult, customersResult] = await Promise.all([
    fetchPortalUnassignedBanks(tenant),
    canViewLinkCustomers
      ? fetchPortalLinkBankCustomers(tenant)
      : Promise.resolve({ items: [], errorMessage: null as string | null }),
  ]);

  return (
    <CustomerPageShell>
      <UnassignedBanksPageClient
        tenant={tenant}
        initialCustomers={customersResult.items}
        initialUnassignedAccounts={unassignedResult.unassignedAccounts}
        initialErrorMessage={unassignedResult.errorMessage ?? customersResult.errorMessage}
        canManage={canManage}
        capabilities={capabilities}
      />
    </CustomerPageShell>
  );
}
