"use client";

import * as React from "react";

import { BankCustomersList } from "@/app/customer/[tenant]/admin/_components/bank-customers-list";
import {
  useAdminListQuery,
  type AdminListPagination,
} from "@/app/customer/[tenant]/admin/_components/use-admin-list-query";
import type { PortalLinkBankCustomerRow } from "@/app/customer/_lib/admin/link-bank-accounts-server-api";
import type { CustomerPortalCapabilities } from "@/lib/frontend-auth/report-capabilities";

import { BankAccountsSheet } from "./bank-accounts-sheet";

type LinkBankAccountsPageClientProps = {
  tenant: string;
  initialCustomers: PortalLinkBankCustomerRow[];
  initialErrorMessage: string | null;
  canManage: boolean;
  capabilities?: CustomerPortalCapabilities | null;
  initialQ: string;
  pagination: AdminListPagination;
};

export function LinkBankAccountsPageClient({
  tenant,
  initialCustomers,
  initialErrorMessage,
  canManage,
  capabilities,
  initialQ,
  pagination,
}: LinkBankAccountsPageClientProps) {
  const {
    searchInput,
    setSearchInput,
    isPending,
    pushListParams,
    rangeStart,
    rangeEnd,
  } = useAdminListQuery({ initialQ, pagination });

  const [rows, setRows] = React.useState(initialCustomers);
  const [selectedCustomer, setSelectedCustomer] =
    React.useState<PortalLinkBankCustomerRow | null>(null);
  const [sheetOpen, setSheetOpen] = React.useState(false);

  const [syncedCustomers, setSyncedCustomers] = React.useState(initialCustomers);
  if (syncedCustomers !== initialCustomers) {
    setSyncedCustomers(initialCustomers);
    setRows(initialCustomers);
  }

  const openSheet = (customer: PortalLinkBankCustomerRow) => {
    setSelectedCustomer(customer);
    setSheetOpen(true);
  };

  const handleSaved = (customerId: number, accountCount: number) => {
    setRows((prev) =>
      prev.map((row) => (row.customerId === customerId ? { ...row, accountCount } : row)),
    );
  };

  return (
    <>
      <BankCustomersList
        tenant={tenant}
        description="Manage bank accounts linked to customers in this book."
        activeTab="link-accounts"
        capabilities={capabilities}
        rows={rows}
        canManage={canManage}
        errorMessage={initialErrorMessage}
        searchValue={searchInput}
        onSearchChange={setSearchInput}
        searchAriaLabel="Search customers"
        emptyMessage={initialQ ? "No customers match your search." : "No customers found."}
        isPending={isPending}
        pagination={pagination}
        rangeStart={rangeStart}
        rangeEnd={rangeEnd}
        onPushPagination={pushListParams}
        pageSizeId="link-bank-accounts-page-size"
        onOpenCustomer={openSheet}
      />

      <BankAccountsSheet
        tenant={tenant}
        customer={selectedCustomer}
        open={sheetOpen}
        canManage={canManage}
        onOpenChange={setSheetOpen}
        onSaved={handleSaved}
      />
    </>
  );
}
