"use client";

import * as React from "react";
import { Wallet } from "lucide-react";

import {
  AdminListPaginationBar,
  AdminListSearchInput,
} from "@/app/customer/[tenant]/admin/_components/admin-list-shell";
import type { AdminListPagination } from "@/app/customer/[tenant]/admin/_components/use-admin-list-query";
import { BankSetupHeader } from "@/app/customer/[tenant]/admin/_components/bank-setup-tabs";
import type { BankSetupTab } from "@/app/customer/[tenant]/admin/_components/bank-setup-tabs";
import type { PortalLinkBankCustomerRow } from "@/app/customer/_lib/admin/link-bank-accounts-server-api";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { CustomerPortalCapabilities } from "@/lib/frontend-auth/report-capabilities";

export type BankCustomerListRow = PortalLinkBankCustomerRow & {
  unassignedCount?: number;
};

type BankCustomersListProps = {
  tenant: string;
  description: string;
  activeTab: BankSetupTab;
  capabilities?: CustomerPortalCapabilities | null;
  rows: BankCustomerListRow[];
  canManage: boolean;
  errorMessage?: string | null;
  searchValue: string;
  onSearchChange: (value: string) => void;
  searchAriaLabel: string;
  emptyMessage: string;
  /** Show the Unassigned-rows column (Unassigned banks tab). */
  showUnassignedCount?: boolean;
  isPending?: boolean;
  pagination?: AdminListPagination;
  rangeStart?: number;
  rangeEnd?: number;
  onPushPagination?: (next: {
    page?: number;
    pageSize?: number;
    q?: string;
  }) => void;
  pageSizeId?: string;
  onOpenCustomer: (row: BankCustomerListRow) => void;
};

/**
 * Shared bank-setup customer table (Link Bank Accounts + Unassigned).
 * Search chrome is owned by the parent (url mode via useAdminListQuery, or local filter).
 */
export function BankCustomersList({
  tenant,
  description,
  activeTab,
  capabilities,
  rows,
  canManage,
  errorMessage,
  searchValue,
  onSearchChange,
  searchAriaLabel,
  emptyMessage,
  showUnassignedCount = false,
  isPending = false,
  pagination,
  rangeStart,
  rangeEnd,
  onPushPagination,
  pageSizeId = "bank-customers-page-size",
  onOpenCustomer,
}: BankCustomersListProps) {
  const colSpan = showUnassignedCount ? 5 : 4;

  return (
    <div className={`flex flex-col gap-4${isPending ? " opacity-70" : ""}`}>
      <BankSetupHeader tenant={tenant} active={activeTab} capabilities={capabilities} />

      <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">
        <p className="text-sm text-muted-foreground">{description}</p>
        <AdminListSearchInput
          value={searchValue}
          onChange={onSearchChange}
          placeholder="Search by name, email, company, or subdomain"
          aria-label={searchAriaLabel}
          className="relative w-full sm:w-80"
          inputClassName="pl-8"
        />
      </div>

      {errorMessage ? (
        <p className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
          {errorMessage}
        </p>
      ) : null}

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/40 hover:bg-muted/40">
              <TableHead className="px-3">Customer</TableHead>
              <TableHead className="px-3">Subdomain</TableHead>
              <TableHead className="px-3 text-center">Bank accounts</TableHead>
              {showUnassignedCount ? (
                <TableHead className="px-3 text-center">Unassigned rows</TableHead>
              ) : null}
              <TableHead className="px-3 text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length ? (
              rows.map((row) => (
                <TableRow key={row.customerId}>
                  <TableCell className="px-3 py-2.5">
                    <div className="flex flex-col">
                      <span className="font-medium">
                        {row.fullName || `#${row.customerId}`}
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {[row.email, row.company].filter(Boolean).join(" · ") ||
                          `Customer #${row.customerId}`}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="px-3 py-2.5 text-muted-foreground">
                    {row.subdomain || "—"}
                  </TableCell>
                  <TableCell className="px-3 py-2.5 text-center">
                    <Badge variant={row.accountCount > 0 ? "secondary" : "outline"}>
                      {row.accountCount}
                    </Badge>
                  </TableCell>
                  {showUnassignedCount ? (
                    <TableCell className="px-3 py-2.5 text-center">
                      <Badge
                        variant={(row.unassignedCount ?? 0) > 0 ? "outline" : "secondary"}
                      >
                        {row.unassignedCount ?? 0}
                      </Badge>
                    </TableCell>
                  ) : null}
                  <TableCell className="px-3 py-2.5 text-right">
                    <Button size="sm" variant="outline" onClick={() => onOpenCustomer(row)}>
                      <Wallet className="size-3.5" />
                      {canManage ? "Manage" : "View"}
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={colSpan} className="h-24 text-center text-muted-foreground">
                  {emptyMessage}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {pagination && onPushPagination && rangeStart !== undefined && rangeEnd !== undefined ? (
        <AdminListPaginationBar
          pagination={pagination}
          isPending={isPending}
          rangeStart={rangeStart}
          rangeEnd={rangeEnd}
          noun="customer"
          pageSizeId={pageSizeId}
          onPush={onPushPagination}
        />
      ) : null}
    </div>
  );
}
