"use client";

import { kindFromFilePathAndName } from "@/app/customer/_lib/dashboard-widget-allowlist";
import type { DashboardSettingsWidget } from "../../_lib/dashboard-widgets-server-api";
import { AssetAllocationConfigPanel } from "./panels/asset-allocation-panel";
import { CashflowCalendarConfigPanel } from "./panels/cashflow-calendar-panel";
import { ConsolidatedHoldingsConfigPanel } from "./panels/consolidated-holdings-panel";
import { DefaultConfigPanel } from "./panels/default-panel";
import { DepositWidgetConfigPanel } from "./panels/deposit-widget-panel";
import { DiyHoldingsConfigPanel } from "./panels/diy-holdings-panel";
import { IsinSelectionConfigPanel } from "./panels/isin-selection-panel";
import { TopGainersConfigPanel } from "./panels/top-gainers-panel";
import type { ConfigureTarget, WidgetConfigDescriptor } from "./types";

/**
 * Extensible registry: add a kind → Panel entry to give a widget its own configure UI.
 * Layout and drawer chrome stay unchanged.
 */
const WIDGET_CONFIG_BY_KIND: Partial<
  Record<
    NonNullable<ReturnType<typeof kindFromFilePathAndName>>,
    WidgetConfigDescriptor
  >
> = {
  asset_allocation: {
    kind: "asset_allocation",
    title: (widget, mode) =>
      mode === "create" ? "Add Asset Allocation Widget" : (widget?.name ?? "Asset Allocation"),
    description: "Set title, report type, and banks for this Asset Allocation widget.",
    size: "wide",
    Panel: AssetAllocationConfigPanel,
  },
  consolidated_holdings: {
    kind: "consolidated_holdings",
    title: (widget, mode) =>
      mode === "create"
        ? "Add Consolidated Holdings Widget"
        : (widget?.name ?? "Consolidated Holdings"),
    description: "Set title, report type, and banks for this Consolidated Holdings widget.",
    size: "wide",
    Panel: ConsolidatedHoldingsConfigPanel,
  },
  diy_consolidated_holdings: {
    kind: "diy_consolidated_holdings",
    title: (widget, mode) =>
      mode === "create" ? "Add DIY Widget" : (widget?.name ?? "DIY Consolidated Holdings"),
    description:
      "Configure grouping levels and asset, bank, and currency filters for this DIY widget.",
    size: "wide",
    Panel: DiyHoldingsConfigPanel,
  },
  cashflow_calendar: {
    kind: "cashflow_calendar",
    title: (widget, mode) =>
      mode === "create" ? "Add Cashflow Widget" : (widget?.name ?? "Cashflow Calendar"),
    description:
      "Configure event types, structure status, banks, and asset classes for this Cashflow widget.",
    size: "wide",
    Panel: CashflowCalendarConfigPanel,
  },
  top_gainers_losers: {
    kind: "top_gainers_losers",
    title: (widget, mode) =>
      mode === "create" ? "Add Top Gainers Widget" : (widget?.name ?? "Top Gainers and Losers"),
    description: "Choose the comparison period used to rank gainers and losers.",
    size: "default",
    Panel: TopGainersConfigPanel,
  },
  deposit: {
    kind: "deposit",
    title: (widget, mode) =>
      mode === "create" ? "Add Deposit Widget" : (widget?.name ?? "Deposit"),
    description: "Configure banks and currencies for this Deposit maturity widget.",
    size: "wide",
    Panel: DepositWidgetConfigPanel,
  },
};

const ISIN_CONFIG: WidgetConfigDescriptor = {
  kind: "isin",
  title: (widget) => widget?.name ?? "ISIN selection",
  description: "Select ISINs used by this widget. Save dashboard settings to apply.",
  size: "default",
  Panel: IsinSelectionConfigPanel,
};

const DEFAULT_CONFIG: WidgetConfigDescriptor = {
  kind: "default",
  title: (widget) => widget?.name ?? "Widget",
  description: "Additional configuration for this widget will appear here when available.",
  size: "default",
  Panel: DefaultConfigPanel,
};

export function resolveWidgetConfig(
  widget: DashboardSettingsWidget | null,
  mode: "edit" | "create" = "edit",
  createKind?: ConfigureTarget["kind"],
): WidgetConfigDescriptor {
  if (mode === "create") {
    if (createKind === "create-aa") return { ...WIDGET_CONFIG_BY_KIND.asset_allocation! };
    if (createKind === "create-ch") return { ...WIDGET_CONFIG_BY_KIND.consolidated_holdings! };
    if (createKind === "create-cf") return { ...WIDGET_CONFIG_BY_KIND.cashflow_calendar! };
    if (createKind === "create-tgl") return { ...WIDGET_CONFIG_BY_KIND.top_gainers_losers! };
    if (createKind === "create-dep") return { ...WIDGET_CONFIG_BY_KIND.deposit! };
    return { ...WIDGET_CONFIG_BY_KIND.diy_consolidated_holdings! };
  }
  if (!widget) return DEFAULT_CONFIG;

  const kind = kindFromFilePathAndName(widget.file_path, widget.name);
  if (kind && WIDGET_CONFIG_BY_KIND[kind]) {
    return WIDGET_CONFIG_BY_KIND[kind]!;
  }
  if (widget.requires_isin_selection) return ISIN_CONFIG;
  return DEFAULT_CONFIG;
}

/** True when the widget has a real Configure panel (not the empty default). */
export function widgetSupportsConfiguration(widget: DashboardSettingsWidget): boolean {
  const descriptor = resolveWidgetConfig(widget);
  return descriptor.kind !== "default";
}

const WIDGET_REMOVE_BY_KIND: Partial<
  Record<
    NonNullable<ReturnType<typeof kindFromFilePathAndName>>,
    { operation: string; confirm: string; success: string }
  >
> = {
  asset_allocation: {
    operation: "asset-remove",
    confirm: "Remove this Asset Allocation widget from your dashboard?",
    success: "Asset Allocation widget removed",
  },
  consolidated_holdings: {
    operation: "consolidated-remove",
    confirm: "Remove this Consolidated Holdings widget from your dashboard?",
    success: "Consolidated Holdings widget removed",
  },
  diy_consolidated_holdings: {
    operation: "diy-remove",
    confirm: "Remove this DIY widget? This will delete it from your dashboard.",
    success: "DIY widget removed",
  },
  cashflow_calendar: {
    operation: "cashflow-remove",
    confirm: "Remove this Cashflow widget from your dashboard?",
    success: "Cashflow widget removed",
  },
  top_gainers_losers: {
    operation: "top-gainers-remove",
    confirm: "Remove this Top Gainers widget from your dashboard?",
    success: "Top Gainers widget removed",
  },
  deposit: {
    operation: "deposit-remove",
    confirm: "Remove this Deposit widget from your dashboard?",
    success: "Deposit widget removed",
  },
};

/** Removable multi-instance widgets (always show Remove next to Configure when present). */
export function getWidgetRemoveAction(
  widget: DashboardSettingsWidget,
): { operation: string; confirm: string; success: string } | null {
  const kind = kindFromFilePathAndName(widget.file_path, widget.name);
  if (!kind) return null;
  return WIDGET_REMOVE_BY_KIND[kind] ?? null;
}

/** Parse deep-link tokens like `aaw-12`, `chw-3`, `diyw-7`, or create-* tokens. */
export function parseConfigureParam(value: string | null | undefined): ConfigureTarget | null {
  if (!value) return null;
  const trimmed = value.trim();
  if (!trimmed) return null;

  if (trimmed === "create-diy" || trimmed === "diy-new") {
    return { kind: "create-diy" };
  }
  if (trimmed === "create-aa" || trimmed === "aa-new") {
    return { kind: "create-aa" };
  }
  if (trimmed === "create-ch" || trimmed === "ch-new") {
    return { kind: "create-ch" };
  }
  if (trimmed === "create-cf" || trimmed === "cf-new" || trimmed === "cashflow-new") {
    return { kind: "create-cf" };
  }
  if (trimmed === "create-tgl" || trimmed === "tgl-new" || trimmed === "top-gainers-new") {
    return { kind: "create-tgl" };
  }
  if (trimmed === "create-dep" || trimmed === "dep-new" || trimmed === "deposit-new") {
    return { kind: "create-dep" };
  }

  const prefixed = /^(?:aaw|chw|diyw|cfw|depw|tglw|widget)-(\d+)$/i.exec(trimmed);
  if (prefixed) {
    const widgetId = Number(prefixed[1]);
    return Number.isFinite(widgetId) && widgetId > 0 ? { kind: "widget", widgetId } : null;
  }

  if (/^\d+$/.test(trimmed)) {
    const widgetId = Number(trimmed);
    return Number.isFinite(widgetId) && widgetId > 0 ? { kind: "widget", widgetId } : null;
  }

  return null;
}

/** Build settings URL configure token for dashboard gear deep-links. */
export function configureParamForWidget(
  family: "aa" | "ch" | "diy" | "cf" | "dep" | "tgl",
  widgetId: number,
): string {
  if (family === "aa") return `aaw-${widgetId}`;
  if (family === "ch") return `chw-${widgetId}`;
  if (family === "cf") return `cfw-${widgetId}`;
  if (family === "dep") return `depw-${widgetId}`;
  if (family === "tgl") return `tglw-${widgetId}`;
  return `diyw-${widgetId}`;
}
