"use client";

import type { ColumnDef } from "@tanstack/react-table";

import type {
  CustomerPagePermissions,
  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 { displayCell, standardAssetLeadColumns } from "@/app/customer/_lib/asset-column-builders";
import { CustomerSortableHeader } from "@/components/customer/customer-table-primitives";
import {
  TransactionRowStockActions,
  type StockChildMenuItem,
} from "@/components/form/transaction-workspace/list-table-form-actions";
import { formatAmount, formatQuantityFixed } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

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

export {
  FALLBACK_STOCK_GRID_COLUMNS as FALLBACK_BOND_FUND_GRID_COLUMNS,
  STOCK_OPTIONS_COLUMN_ID as BOND_FUND_OPTIONS_COLUMN_ID,
} from "@/app/customer/[tenant]/stock/_components/list-stocks-table/columns";

export type BondFundColumnFormatOptions = {
  priceDecimals?: number;
  quantityDecimals?: number;
  listPath?: string;
  pagePermissions?: CustomerPagePermissions;
};

function buildBondFundSaleFormHref(listPath: string, parentId: string): string {
  const params = new URLSearchParams({ pid: parentId.trim() });
  return `${listPath}/form?${params.toString()}`;
}

function canShowBondFundSaleAction(
  rowFlag: boolean | undefined,
  rowUrl: string | null | undefined,
  pageFlag: boolean | undefined,
  row: BondFundRow,
): boolean {
  if (rowFlag || rowUrl) {
    return true;
  }

  return Boolean(pageFlag && row.isBondFundPurchase === true);
}

function buildBondFundChildMenuItems(
  row: BondFundRow,
  listPath?: string,
  pagePermissions?: CustomerPagePermissions,
): StockChildMenuItem[] {
  if (!listPath || !row.id || row.isBondFundPurchase === false) {
    return [];
  }

  if (
    !canShowBondFundSaleAction(
      row.permissions?.create_sale,
      row.saleUrl,
      pagePermissions?.create || pagePermissions?.sale_create,
      row,
    )
  ) {
    return [];
  }

  return [
    {
      key: "sale",
      label: "Sale",
      href: buildBondFundSaleFormHref(listPath, row.id),
    },
  ];
}



export function createBondFundColumns(
  gridColumns: CustomerGridColumn[] | undefined,
  onView: (row: BondFundRow) => void,
  onEdit: ((row: BondFundRow) => void) | undefined,
  options: BondFundColumnFormatOptions = {},
): ColumnDef<BondFundRow>[] {
  const priceDecimals = options.priceDecimals ?? 2;
  const quantityDecimals = options.quantityDecimals ?? 2;

  return [
    ...standardAssetLeadColumns<BondFundRow>({ gridColumns }),
    {
      id: "security_ticker",
      accessorKey: "ticker",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "security_ticker", "Ticker")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="whitespace-nowrap font-mono text-xs">{displayCell(row.original.ticker)}</span>
      ),
    },
    {
      id: "name",
      accessorKey: "name",
      header: ({ column }) => (
        <CustomerSortableHeader label={labelForGridColumn(gridColumns, "name", "Name")} column={column} />
      ),
      cell: ({ row }) => <span className="min-w-48 text-sm leading-snug">{row.original.name}</span>,
    },
    {
      id: "category",
      accessorKey: "type",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "category", "Type")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{row.original.type}</span>,
    },
    {
      id: "execution_type",
      accessorKey: "executionType",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "execution_type", "Execution Type")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{row.original.executionType}</span>,
    },
    {
      id: "transaction_type",
      accessorKey: "transaction",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "transaction_type", "Transaction")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{row.original.transaction}</span>,
    },
    {
      id: "price_formatted",
      accessorKey: "price",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "price_formatted", "Price")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="block text-right text-sm tabular-nums">
          {row.original.priceDisplay ?? row.original.price.toFixed(priceDecimals)}
        </span>
      ),
    },
    {
      id: "quantity_formatted",
      accessorKey: "quantity",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "quantity_formatted", "Quantity")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="block text-right text-sm tabular-nums">
          {row.original.quantityDisplay ?? formatQuantityFixed(row.original.quantity, quantityDecimals)}
        </span>
      ),
    },
    {
      id: "currency",
      accessorKey: "currency",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "currency", "Currency")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{row.original.currency}</span>,
    },
    {
      id: "amount_formatted",
      accessorKey: "amount",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "amount_formatted", "Amount")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span
          className={cn(
            "block text-right font-medium text-sm tabular-nums",
            row.original.amount < 0
              ? "text-red-600 dark:text-red-400"
              : row.original.amount > 0
                ? "text-green-600 dark:text-green-400"
                : "",
          )}
        >
          {formatAmount(row.original.amount)}
        </span>
      ),
    },
    {
      id: "options",
      header: () => <span className="font-medium text-sm">Options</span>,
      cell: ({ row }) => {
        const { canView, canEdit } = resolveRowActionPermissions(
          row.original.permissions as CustomerRowPermissions,
          { allowViewFallback: false, allowEditFallback: false },
        );
        const childMenuItems = buildBondFundChildMenuItems(
          row.original,
          options.listPath,
          options.pagePermissions,
        );

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

        return (
          <TransactionRowStockActions
            rowName={row.original.name}
            canView={canView}
            canEdit={canEdit && Boolean(onEdit)}
            childMenuItems={childMenuItems}
            onView={() => onView(row.original)}
            onEdit={onEdit ? () => onEdit(row.original) : undefined}
          />
        );
      },
      enableSorting: false,
    },
  ];
}
