"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { displayCell } from "@/app/customer/_lib/asset-column-builders";

import {
  labelForGridColumn,
  type CustomerGridColumn,
} from "@/app/customer/_lib/customer-grid-columns";
import { CustomerSortableHeader } from "@/components/customer/customer-table-primitives";
import { formatAmount } from "@/lib/format/numbers";

import type { CashRow } from "./schema";

export const FALLBACK_CASH_GRID_COLUMNS: CustomerGridColumn[] = [
  { key: "account_id", label: "Account ID", defaultVisible: true },
  { key: "bank", label: "Bank", defaultVisible: true },
  { key: "currency", label: "Currency", defaultVisible: true },
  { key: "amount_formatted", label: "Amount", defaultVisible: true },
];


/** Cash balance columns matching the old Yii layout: Account ID, Bank, Currency, Amount. */
export function createCashColumns(
  gridColumns: CustomerGridColumn[] | undefined,
  _onView: (row: CashRow) => void,
  _onEdit?: (row: CashRow) => void,
): ColumnDef<CashRow>[] {
  return [
    {
      id: "account_id",
      accessorKey: "accountId",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "account_id", "Account ID")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="whitespace-nowrap text-sm">{displayCell(row.original.accountId)}</span>
      ),
    },
    {
      id: "bank",
      accessorKey: "bank",
      header: ({ column }) => (
        <CustomerSortableHeader label={labelForGridColumn(gridColumns, "bank", "Bank")} column={column} />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.bank)}</span>,
    },
    {
      id: "currency",
      accessorKey: "currency",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "currency", "Currency")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.currency)}</span>,
    },
    {
      id: "amount_formatted",
      accessorKey: "amount",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "amount_formatted", "Amount")}
          column={column}
        />
      ),
      cell: ({ row }) => {
        if (row.original.amountEmpty) {
          return <span className="block text-right text-sm tabular-nums" />;
        }

        return (
          <span className="block text-right text-sm tabular-nums">
            {row.original.amountDisplay ?? formatAmount(row.original.amount)}
          </span>
        );
      },
    },
  ];
}
