"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { displayCell, standardAssetLeadColumns } from "@/app/customer/_lib/asset-column-builders";
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 { 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 { OtherAssetRow } from "./schema";

export const OTHER_ASSET_OPTIONS_COLUMN_ID = "options";

export const FALLBACK_OTHER_ASSET_GRID_COLUMNS: CustomerGridColumn[] = [
  { key: "uid_title", label: "Ref. ID", defaultVisible: true },
  { key: "placement_date", label: "Placement Date", defaultVisible: true },
  { key: "bank", label: "Bank", defaultVisible: true },
  { key: "security_ticker", label: "Ticker", defaultVisible: true },
  { key: "name", label: "Name", defaultVisible: true },
  { key: "asset_type", label: "Type", defaultVisible: true },
  { key: "execution_type", label: "Execution Type", defaultVisible: true },
  { key: "transaction_type", label: "Transaction", defaultVisible: true },
  { key: "price_formatted", label: "Price", defaultVisible: true },
  { key: "quantity_formatted", label: "Quantity", defaultVisible: true },
  { key: "currency", label: "Currency", defaultVisible: true },
  { key: "amount_formatted", label: "Amount", defaultVisible: true },
];

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

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

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

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

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

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

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



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

  return [
    ...standardAssetLeadColumns<OtherAssetRow>({ 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: "asset_type",
      accessorKey: "type",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "asset_type", "Type")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(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"
                : "",
          )}
        >
          {row.original.amountDisplay ?? formatAmount(row.original.amount)}
        </span>
      ),
    },
    {
      id: OTHER_ASSET_OPTIONS_COLUMN_ID,
      header: () => <span className="font-medium text-sm">Options</span>,
      enableHiding: false,
      cell: ({ row }) => {
        const { canView, canEdit } = resolveRowActionPermissions(
          row.original.permissions as CustomerRowPermissions,
          { allowViewFallback: false, allowEditFallback: false },
        );
        const childMenuItems = buildOtherAssetChildMenuItems(
          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,
    },
  ];
}
