"use client";

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

import type { CustomerRowPermissions } from "@/app/customer/_lib/customer-api-permissions";
import { resolveRowActionPermissions } from "@/app/customer/_lib/customer-api-permissions";
import {
  labelForGridColumn,
  type CustomerGridColumn,
} from "@/app/customer/_lib/customer-grid-columns";
import { CustomerSortableHeader } from "@/components/customer/customer-table-primitives";
import { Button } from "@/components/ui/button";
// FX accumulator quantities carry no fixed precision, so this uses the shared
// variable-precision helper (0-4 digits) rather than a pinned decimal count.
import { formatAmount, formatQuantity } from "@/lib/format/numbers";
import { formatApiDate } from "@/lib/format/dates";
import { cn } from "@/lib/utils";

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

export const FX_ACCUMULATOR_OPTIONS_COLUMN_ID = "options";

export const FALLBACK_FX_ACCUMULATOR_GRID_COLUMNS: CustomerGridColumn[] = [
  { key: "placement_date", label: "Placement Date", defaultVisible: true },
  { key: "uid_title", label: "Ref. ID", defaultVisible: true },
  { key: "transaction_type", label: "Type of Transaction", defaultVisible: true },
  { key: "security_name", label: "Security Name / Security Ticket", defaultVisible: true },
  { key: "quantity_formatted", label: "Quantity (Total)", defaultVisible: true },
  { key: "amount_formatted", label: "Max Exposure", defaultVisible: true },
];



/** FX Accumulator columns matching Yii1 list order (see FxAccumulator::gridColumns). */
export function createFxAccumulatorColumns(
  gridColumns: CustomerGridColumn[] | undefined,
  onView: (row: FxAccumulatorRow) => void,
): ColumnDef<FxAccumulatorRow>[] {
  return [
    {
      id: "placement_date",
      accessorKey: "placementDate",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "placement_date", "Placement Date")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="whitespace-nowrap text-sm">
          {formatApiDate(row.original.placementDate, "dd MMM yyyy", row.original.placementDate)}
        </span>
      ),
    },
    {
      id: "uid_title",
      accessorKey: "refId",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "uid_title", "Ref. ID")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="whitespace-nowrap text-sm">{row.original.refId}</span>,
    },
    {
      id: "transaction_type",
      accessorKey: "transaction",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "transaction_type", "Type of Transaction")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.transaction)}</span>,
    },
    {
      id: "security_name",
      accessorKey: "securityName",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(
            gridColumns,
            "security_name",
            "Security Name / Security Ticket",
          )}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.securityName)}</span>,
    },
    {
      id: "quantity_formatted",
      accessorKey: "quantity",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "quantity_formatted", "Quantity (Total)")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="block text-right text-sm tabular-nums">
          {row.original.quantityDisplay ?? formatQuantity(row.original.quantity)}
        </span>
      ),
    },
    {
      id: "amount_formatted",
      accessorKey: "amount",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "amount_formatted", "Max Exposure")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span
          className={cn(
            "block text-right font-medium text-sm tabular-nums",
            row.original.amountNegative
              ? "text-red-600 dark:text-red-400"
              : row.original.amountPositive
                ? "text-green-600 dark:text-green-400"
                : "",
          )}
        >
          {row.original.amountDisplay ?? formatAmount(row.original.amount)}
        </span>
      ),
    },
    {
      id: FX_ACCUMULATOR_OPTIONS_COLUMN_ID,
      header: () => <span className="font-medium text-sm">Options</span>,
      cell: ({ row }) => {
        const { canView } = resolveRowActionPermissions(
          row.original.permissions as CustomerRowPermissions,
          { allowViewFallback: false, allowEditFallback: false },
        );

        if (!canView) {
          return <span className="block text-center text-muted-foreground text-sm">—</span>;
        }

        return (
          <div className="flex w-full items-center justify-end gap-0.5">
            <Button
              variant="ghost"
              size="icon-sm"
              className="text-teal-600 hover:bg-teal-500/10 hover:text-teal-700 dark:text-teal-400"
              onClick={() => onView(row.original)}
            >
              <Eye className="size-4" />
              <span className="sr-only">View details for {row.original.refId}</span>
            </Button>
          </div>
        );
      },
      enableSorting: false,
    },
  ];
}
