"use client";

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

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import type { PortalLinkBankCustomerRow } from "@/app/customer/_lib/admin/link-bank-accounts-server-api";
import { BankSetupTabs } from "@/app/customer/[tenant]/admin/_components/bank-setup-tabs";

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

type LinkBankAccountsPageClientProps = {
  tenant: string;
  initialCustomers: PortalLinkBankCustomerRow[];
  initialErrorMessage: string | null;
  canManage: boolean;
};

export function LinkBankAccountsPageClient({
  tenant,
  initialCustomers,
  initialErrorMessage,
  canManage,
}: LinkBankAccountsPageClientProps) {
  const [rows, setRows] = React.useState(initialCustomers);
  const [search, setSearch] = React.useState("");
  const [selectedCustomer, setSelectedCustomer] =
    React.useState<PortalLinkBankCustomerRow | null>(null);
  const [sheetOpen, setSheetOpen] = React.useState(false);

  const filtered = React.useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) =>
      [row.fullName, row.email, row.company, row.subdomain, String(row.customerId)]
        .join(" ")
        .toLowerCase()
        .includes(q),
    );
  }, [rows, search]);

  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 (
    <>
      <div className="flex flex-col gap-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <div className="flex items-center gap-2">
              <Landmark className="size-5 text-muted-foreground" />
              <h1 className="text-2xl tracking-tight">Link Bank Accounts</h1>
            </div>
            <p className="mt-1 text-sm text-muted-foreground">
              Manage bank accounts linked to customers in this book.
            </p>
          </div>
        </div>

        <BankSetupTabs tenant={tenant} active="link-accounts" />

        <div className="relative w-full max-w-sm">
          <Search className="pointer-events-none absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={search}
            placeholder="Search by name, email, company, or subdomain"
            className="pl-8"
            onChange={(event) => setSearch(event.target.value)}
          />
        </div>

        {initialErrorMessage ? (
          <p className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
            {initialErrorMessage}
          </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>
                <TableHead className="px-3 text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.length ? (
                filtered.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>
                    <TableCell className="px-3 py-2.5 text-right">
                      <Button size="sm" variant="outline" onClick={() => openSheet(row)}>
                        <Wallet className="size-3.5" />
                        {canManage ? "Manage" : "View"}
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={4} className="h-24 text-center text-muted-foreground">
                    No customers found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>

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