import type { CustomerGridColumn } from "@/app/customer/_lib/customer-grid-columns";

import type {
  StructuredProductLegacyField,
  StructuredProductSortColumn,
} from "../../_lib/structured-product-types";
import { STRUCTURED_PRODUCT_COLUMNS } from "./schema";

export type StructuredProductColumnFilterKey =
  | "isin"
  | "productTypes"
  | "underlyingIsin"
  | "underlying";

export type StructuredProductColumnDef = CustomerGridColumn & {
  field: StructuredProductLegacyField;
  sortColumn?: StructuredProductSortColumn;
  filterKey?: StructuredProductColumnFilterKey;
};

const FILTER_KEY_BY_FIELD: Partial<
  Record<StructuredProductLegacyField, StructuredProductColumnFilterKey>
> = {
  s_isinInit: "isin",
  product_typeAbsolute: "productTypes",
  UnderlyingISIN1: "underlyingIsin",
  Underlying1: "underlying",
};

/** No locked columns — ISIN and Product may be shown or hidden like other fields. */
export const STRUCTURED_PRODUCT_LOCKED_KEYS: StructuredProductLegacyField[] = [];

/** Per-column footer/strip total toggles (not data columns). */
export const STRUCTURED_PRODUCT_TOTAL_TOGGLE_KEYS = [
  "totalNotional",
  "totalIndicativeCoupon",
  "totalIndicativeAnnualCoupon",
] as const;

export type StructuredProductTotalToggleKey =
  (typeof STRUCTURED_PRODUCT_TOTAL_TOGGLE_KEYS)[number];

export const STRUCTURED_PRODUCT_TOTAL_TOGGLE_BY_FIELD: Record<
  "Notional" | "IndicativeCoupon" | "IndicativeAnnualCoupon",
  StructuredProductTotalToggleKey
> = {
  Notional: "totalNotional",
  IndicativeCoupon: "totalIndicativeCoupon",
  IndicativeAnnualCoupon: "totalIndicativeAnnualCoupon",
};

export const STRUCTURED_PRODUCT_TOTAL_TOGGLE_ENTRIES: CustomerGridColumn[] = [
  { key: "totalNotional", label: "Total · Notional", defaultVisible: true },
  {
    key: "totalIndicativeCoupon",
    label: "Total · Indicative annual coupon change",
    defaultVisible: true,
  },
  {
    key: "totalIndicativeAnnualCoupon",
    label: "Total · Indicative Annual Coupon",
    defaultVisible: true,
  },
];

const TOTAL_TOGGLE_KEY_SET = new Set<string>(STRUCTURED_PRODUCT_TOTAL_TOGGLE_KEYS);

export const STRUCTURED_PRODUCT_GRID_COLUMNS: StructuredProductColumnDef[] =
  STRUCTURED_PRODUCT_COLUMNS.map((column) => ({
    key: column.field,
    label: column.label,
    field: column.field,
    sortColumn: column.sortColumn,
    filterKey: FILTER_KEY_BY_FIELD[column.field],
  }));

/** Catalog for the Fields panel — totals sit inline next to their columns. */
export const STRUCTURED_PRODUCT_FIELDS_CATALOG: CustomerGridColumn[] = [
  ...STRUCTURED_PRODUCT_GRID_COLUMNS.map((column) => {
    const totalKey =
      STRUCTURED_PRODUCT_TOTAL_TOGGLE_BY_FIELD[
        column.field as keyof typeof STRUCTURED_PRODUCT_TOTAL_TOGGLE_BY_FIELD
      ];
    if (!totalKey) return column;
    return {
      ...column,
      companion: { key: totalKey, label: "Total" },
    };
  }),
  // Prefs-only entries so Total toggles persist (hidden from the list via companionOnlyKeys).
  ...STRUCTURED_PRODUCT_TOTAL_TOGGLE_ENTRIES,
];

export const STRUCTURED_PRODUCT_FOOTER_FIELDS = new Set<StructuredProductLegacyField>([
  "Notional",
  "IndicativeCoupon",
  "IndicativeAnnualCoupon",
]);

export function isStructuredProductTotalToggleKey(key: string): key is StructuredProductTotalToggleKey {
  return TOTAL_TOGGLE_KEY_SET.has(key);
}

export function resolveStructuredProductVisibleColumns(
  order: string[],
  visibility: Record<string, boolean>,
): StructuredProductColumnDef[] {
  const byKey = new Map(
    STRUCTURED_PRODUCT_GRID_COLUMNS.map((column) => [column.key, column]),
  );
  const ordered: StructuredProductColumnDef[] = [];
  for (const key of order) {
    if (isStructuredProductTotalToggleKey(key)) continue;
    const column = byKey.get(key);
    if (!column || visibility[column.key] === false) continue;
    ordered.push(column);
  }
  for (const column of STRUCTURED_PRODUCT_GRID_COLUMNS) {
    if (visibility[column.key] === false) continue;
    if (ordered.some((entry) => entry.key === column.key)) continue;
    ordered.push(column);
  }
  return ordered;
}
