"use client";

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

import type { CustomerRowPermissions, StockPagePermissions } 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,
  formatQuantity as formatQuantityRange,
} from "@/lib/format/numbers";
import { cn } from "@/lib/utils";
import { buildStockChildFormHref } from "@/app/customer/[tenant]/stock/_lib/stock-child-types";

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

export const STOCK_OPTIONS_COLUMN_ID = "options";

export const FALLBACK_STOCK_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: "Security Ticker", defaultVisible: true },
  { key: "name", label: "Name", defaultVisible: true },
  { key: "category", label: "Category", defaultVisible: true },
  { key: "execution_type", label: "Execution Type", defaultVisible: true },
  { key: "transaction_type", label: "Type of 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 StockColumnFormatOptions = {
  priceDecimals?: number;
  quantityUseLocale?: boolean;
  quantityDecimals?: number;
  listPath?: string;
  pagePermissions?: StockPagePermissions;
};

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

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

function buildStockChildMenuItems(
  row: StockRow,
  listPath?: string,
  pagePermissions?: StockPagePermissions,
): StockChildMenuItem[] {
  if (row.isRedeemed || /\(redeemed\)/i.test(row.type)) {
    return [];
  }

  if (!listPath || !row.id) {
    return [];
  }

  const items: StockChildMenuItem[] = [];
  const permissions = row.permissions;

  if (
    canShowStockChildAction(
      permissions.create_sale,
      row.saleUrl,
      pagePermissions?.sale_create,
      row,
    )
  ) {
    items.push({
      key: "sale",
      label: "Sale",
      href: buildStockChildFormHref(listPath, "sale", row.id),
    });
  }
  if (
    canShowStockChildAction(
      permissions.create_option,
      row.optionUrl,
      pagePermissions?.option_create,
      row,
    )
  ) {
    items.push({
      key: "option",
      label: "Option",
      href: buildStockChildFormHref(listPath, "option", row.id),
    });
  }
  if (
    canShowStockChildAction(
      permissions.create_accumulator,
      row.accumulatorUrl,
      pagePermissions?.accumulator_create,
      row,
    )
  ) {
    items.push({
      key: "accumulator",
      label: "Accumulator",
      href: buildStockChildFormHref(listPath, "accumulator", row.id),
    });
  }
  if ((permissions.mark_expired || row.markExpiredUrl) && row.markExpiredUrl) {
    const markExpiredRoute = row.markExpiredUrl.toLowerCase().replace(/[-_]/g, "");
    const fType = markExpiredRoute.includes("bondfundsaccumulator")
      ? "Ad"
      : markExpiredRoute.includes("bondaccumulator")
        ? "Ab"
        : "";
    let markExpiredHref = `${buildStockChildFormHref(listPath, "mark_expired", row.id)}&markAsExpired=${encodeURIComponent(row.id)}`;
    if (fType) {
      markExpiredHref += `&f_type=${encodeURIComponent(fType)}`;
    }
    items.push({
      key: "mark_expired",
      label: "Mark Expired",
      href: markExpiredHref,
    });
  }

  return items;
}



function formatQuantity(value: number, options: StockColumnFormatOptions) {
  // `quantityUseLocale` selects variable precision (0-4 digits) over the pinned
  // decimal count; both render in en-US so SSR and client agree.
  if (options.quantityUseLocale) {
    return formatQuantityRange(value);
  }

  return formatQuantityFixed(value, options.quantityDecimals ?? 2);
}

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

  return [
    ...standardAssetLeadColumns<StockRow>({ gridColumns }),
    {
      id: "security_ticker",
      accessorKey: "ticker",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "security_ticker", "Security 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", "Category")}
          column={column}
        />
      ),
      cell: ({ row }) => {
        const typeLabel = row.original.type.trim();
        const showRedeemed =
          row.original.isRedeemed === true || /\(redeemed\)/i.test(typeLabel);
        const baseType = typeLabel.replace(/\s*\(redeemed\)\s*/gi, "").trim() || typeLabel;

        if (!showRedeemed) {
          return <span className="text-sm">{displayCell(typeLabel)}</span>;
        }

        return (
          <span className="text-sm">
            {baseType}{" "}
            <span className="text-red-600 dark:text-red-400">(Redeemed)</span>
          </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", "Type of 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.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">
          {formatQuantity(row.original.quantity, options)}
        </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: STOCK_OPTIONS_COLUMN_ID,
      header: () => <span className="font-medium text-sm">Options</span>,
      enableHiding: false,
      cell: ({ row }) => {
        const resolvedPermissions = resolveRowActionPermissions(
          row.original.permissions as CustomerRowPermissions,
          { allowViewFallback: false, allowEditFallback: false },
        );
        const canView = resolvedPermissions.canView || Boolean(row.original.viewUrl);
        const canEdit = resolvedPermissions.canEdit || Boolean(row.original.updateUrl);
        const childMenuItems = buildStockChildMenuItems(
          row.original,
          options.listPath,
          options.pagePermissions,
        );

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