"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 { buildMixedFundChildFormHref } from "@/app/customer/[tenant]/mixed-funds/_lib/mixed-funds-child-types";
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 { MixedFundRow } from "./schema";

export const MIXED_FUND_OPTIONS_COLUMN_ID = "options";

/** Yii1 mixed_funds/list column set. */
export const FALLBACK_MIXED_FUND_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: "category", 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 MixedFundColumnFormatOptions = {
  listPath?: string;
  pagePermissions?: StockPagePermissions;
};

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

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

function buildMixedFundChildMenuItems(
  row: MixedFundRow,
  listPath?: string,
  pagePermissions?: StockPagePermissions,
): StockChildMenuItem[] {
  if (!listPath || !row.id || row.isMixedFundPurchase === false) {
    return [];
  }

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

  if (
    canShowMixedFundChildAction(
      permissions?.create_sale,
      row.saleUrl,
      pagePermissions?.sale_create,
      row,
    )
  ) {
    items.push({
      key: "sale",
      label: "Sale",
      href: buildMixedFundChildFormHref(listPath, "sale", row.id),
    });
  }
  if (
    canShowMixedFundChildAction(
      permissions?.create_option,
      row.optionUrl,
      pagePermissions?.option_create,
      row,
    )
  ) {
    items.push({
      key: "option",
      label: "Option",
      href: buildMixedFundChildFormHref(listPath, "option", row.id),
    });
  }
  if (
    canShowMixedFundChildAction(
      permissions?.create_accumulator,
      row.accumulatorUrl,
      pagePermissions?.accumulator_create,
      row,
    )
  ) {
    items.push({
      key: "accumulator",
      label: "Accumulator",
      href: buildMixedFundChildFormHref(listPath, "accumulator", row.id),
    });
  }

  return items;
}


export function createMixedFundColumns(
  gridColumns: CustomerGridColumn[] | undefined,
  onView: (row: MixedFundRow) => void,
  onEdit: ((row: MixedFundRow) => void) | undefined,
  options: MixedFundColumnFormatOptions = {},
): ColumnDef<MixedFundRow>[] {
  return [
    ...standardAssetLeadColumns<MixedFundRow>({ 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">{displayCell(row.original.name)}</span>
      ),
    },
    {
      id: "category",
      accessorKey: "type",
      header: ({ column }) => (
        <CustomerSortableHeader label={labelForGridColumn(gridColumns, "category", "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">{displayCell(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">{displayCell(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(2)}
        </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, 2)}
        </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 }) => (
        <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: MIXED_FUND_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 canEditRow = canEdit || Boolean(row.original.updateUrl);
        const childMenuItems = buildMixedFundChildMenuItems(
          row.original,
          options.listPath,
          options.pagePermissions,
        );

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

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