"use client";

import * as React from "react";

import { CustomerStandardAssetListTable } from "@/app/customer/_components/customer-standard-asset-list-table";
import { useCustomerPortalSession } from "@/app/customer/_components/customer-portal-session-context";
import type { CustomerTransactionModuleId } from "@/app/customer/_lib/customer-asset-modules";
import { useCustomerModuleListPath } from "@/components/form/transaction-workspace/list-table-form-actions";
import { swapsFormConfig } from "@/components/form/transaction-workspace/module-configs";

import {
  createSwapsColumns,
  FALLBACK_SWAPS_GRID_COLUMNS,
  SWAPS_OPTIONS_COLUMN_ID,
} from "../../../swaps/_components/list-swaps-table/columns";
import { SwapsDetailSheet } from "../../../swaps/_components/list-swaps-table/swaps-detail-sheet";
import type { SwapRow } from "../../../swaps/_components/list-swaps-table/schema";
import {
  buildSwapsPageSearchParams,
  DEFAULT_SWAPS_PAGE_SIZE,
  DEFAULT_SWAPS_SORTING,
  EMPTY_SWAPS_FILTERS,
  getSwapsFilterColumnValue,
  parseSwapsPageStateFromSearchParams,
  placementDateRangeToSwapsFilters,
  setSwapsFilterColumnValue,
} from "../../../swaps/_lib/swaps-filters";
import { saveDerivativesCashColumnPrefsClient } from "../../_lib/derivatives-cash-api";
import type { DerivativesCashPagePermissions } from "../../_lib/derivatives-cash-server-api";
import { useDerivativesCashList } from "../../_lib/use-derivatives-cash-list";
import { DerivativesCashCreateMenu } from "../derivatives-cash-create-menu";
import { usePortfolioScopePageReset } from "@/app/customer/_lib/admin/use-portfolio-scope-page-reset";

function isFxAccumulatorRow(row: SwapRow): boolean {
  const fType = String(row.fType ?? "").trim().toLowerCase();
  if (fType === "fa") return true;
  const updateUrl = String(row.updateUrl ?? "").toLowerCase();
  return updateUrl.includes("fx_accumulator") || updateUrl.includes("fx-accumulator");
}

/**
 * Own component so the session hook stays out of the toolbarActions render callback.
 * Takes the module's own permission type: the shared table surfaces permissions as
 * StockPagePermissions, which is assignable here but hides `fx_accumulator_create`.
 */
function DerivativesCashToolbar({
  permissions,
}: {
  permissions: DerivativesCashPagePermissions;
}) {
  const { canCreateTransactions } = useCustomerPortalSession();
  const showCreateMenu =
    canCreateTransactions && Boolean(permissions.fx_accumulator_create || permissions.create);

  return showCreateMenu ? <DerivativesCashCreateMenu permissions={permissions} /> : null;
}

export function ListDerivativesCashTable() {
  const swapsPath = useCustomerModuleListPath("/customer/fx-currency/swaps");
  const fxAccumulatorPath = useCustomerModuleListPath("/customer/fx-currency/fx-accumulator");

  // This hub lists swaps and FX accumulators together, so edit navigation and the
  // delete/update module have to be resolved per row rather than per page.
  const resolveFormListPath = React.useCallback(
    (row: SwapRow) => (isFxAccumulatorRow(row) ? fxAccumulatorPath : swapsPath),
    [fxAccumulatorPath, swapsPath],
  );

  const resolveModuleId = React.useCallback(
    (row: SwapRow): CustomerTransactionModuleId =>
      isFxAccumulatorRow(row) ? "fx-accumulator" : "swaps",
    [],
  );

  return (
    <CustomerStandardAssetListTable
      title="List Derivatives"
      emptyMessage="No derivative records found."
      rowsPerPageId="derivatives-cash-rows-per-page"
      singularName="Derivative"
      formConfig={{ listPath: swapsFormConfig.listPath, newButtonLabel: "New derivative" }}
      resolveEditListPath={resolveFormListPath}
      resolveModuleId={resolveModuleId}
      optionsColumnId={SWAPS_OPTIONS_COLUMN_ID}
      fallbackColumns={FALLBACK_SWAPS_GRID_COLUMNS}
      defaultPageSize={DEFAULT_SWAPS_PAGE_SIZE}
      defaultSorting={DEFAULT_SWAPS_SORTING}
      emptyFilters={EMPTY_SWAPS_FILTERS}
      useList={useDerivativesCashList}
      saveColumnPrefs={saveDerivativesCashColumnPrefsClient}
      parsePageState={parseSwapsPageStateFromSearchParams}
      buildPageSearchParams={buildSwapsPageSearchParams}
      getFilterColumnValue={getSwapsFilterColumnValue}
      setFilterColumnValue={setSwapsFilterColumnValue}
      placementDateRangeToFilters={placementDateRangeToSwapsFilters}
      createColumns={createSwapsColumns}
      DetailSheet={SwapsDetailSheet}
      showNewButton={false}
      toolbarActions={({ permissions }) => <DerivativesCashToolbar permissions={permissions} />}
    />
  );
}
