"use client";

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

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 { TransactionRowPermissionActions } from "@/components/form/transaction-workspace/list-table-form-actions";
import { formatAmount, formatQuantity } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

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

export const INTEREST_DIVIDEND_OPTIONS_COLUMN_ID = "options";

export const FALLBACK_INTEREST_DIVIDEND_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: "quantity_formatted", label: "Quantity", defaultVisible: true },
  { key: "transaction_category", label: "Transaction Type", defaultVisible: true },
  { key: "interest_source_type", label: "Type", defaultVisible: true },
  { key: "interest_mode", label: "Interest Type", defaultVisible: true },
  { key: "transaction_ref", label: "Transaction Ref. #", defaultVisible: true },
  { key: "r_no", label: "Bank Advice Ref No", defaultVisible: true },
  { key: "total_formatted", label: "Total", defaultVisible: true },
  { key: "net_formatted", label: "Net Amount", defaultVisible: true },
];


function formatSignedAmount(
  value: number,
  display?: string,
  negative?: boolean,
) {
  const formatted = display ?? formatAmount(value);

  return (
    <span
      className={cn(
        "block text-right font-medium text-sm tabular-nums",
        negative || value < 0
          ? "text-red-600 dark:text-red-400"
          : value > 0
            ? "text-green-600 dark:text-green-400"
            : "",
      )}
    >
      {formatted}
    </span>
  );
}

/** Interest / dividend columns matching Yii list order (see InterestDivident::gridColumns). */
export function createInterestDividendColumns(
  gridColumns: CustomerGridColumn[] | undefined,
  onView: (row: InterestDividendRow) => void,
  onEdit?: (row: InterestDividendRow) => void,
): ColumnDef<InterestDividendRow>[] {
  return [
    ...standardAssetLeadColumns<InterestDividendRow>({ gridColumns }),
    {
      id: "quantity_formatted",
      accessorKey: "quantity",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "quantity_formatted", "Quantity")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="text-sm">
          {row.original.quantity ? formatQuantity(row.original.quantity) : "—"}
        </span>
      ),
    },
    {
      id: "transaction_category",
      accessorKey: "transactionCategory",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "transaction_category", "Transaction Type")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="text-sm">{displayCell(row.original.transactionCategory)}</span>
      ),
    },
    {
      id: "interest_source_type",
      accessorKey: "interestSourceType",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "interest_source_type", "Type")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="text-sm">{displayCell(row.original.interestSourceType)}</span>
      ),
    },
    {
      id: "interest_mode",
      accessorKey: "interestMode",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "interest_mode", "Interest Type")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.interestMode)}</span>,
    },
    {
      id: "transaction_ref",
      accessorKey: "transactionRef",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "transaction_ref", "Transaction Ref. #")}
          column={column}
        />
      ),
      cell: ({ row }) => (
        <span className="text-sm">{displayCell(row.original.transactionRef)}</span>
      ),
    },
    {
      id: "r_no",
      accessorKey: "rNo",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "r_no", "Bank Advice Ref No")}
          column={column}
        />
      ),
      cell: ({ row }) => <span className="text-sm">{displayCell(row.original.rNo)}</span>,
    },
    {
      id: "total_formatted",
      accessorKey: "total",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "total_formatted", "Total")}
          column={column}
        />
      ),
      cell: ({ row }) =>
        formatSignedAmount(
          row.original.total,
          row.original.totalDisplay,
          row.original.totalNegative,
        ),
    },
    {
      id: "net_formatted",
      accessorKey: "net",
      header: ({ column }) => (
        <CustomerSortableHeader
          label={labelForGridColumn(gridColumns, "net_formatted", "Net Amount")}
          column={column}
        />
      ),
      cell: ({ row }) =>
        formatSignedAmount(row.original.net, row.original.netDisplay, row.original.netNegative),
    },
    {
      id: INTEREST_DIVIDEND_OPTIONS_COLUMN_ID,
      header: () => <span className="font-medium text-sm">Options</span>,
      cell: ({ row }) => {
        const { canView, canEdit } = resolveRowActionPermissions(
          row.original.permissions as CustomerRowPermissions,
          { allowViewFallback: false, allowEditFallback: false },
        );

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

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