import type {
  ResourceColumn,
  RuleEngineResourceConfig,
} from "@/pages/ruleEngine/config/resources";

const TITLE_KEY_PRIORITY = [
  "cargoTypeName",
  "serviceName",
  "name",
  "label",
  "actionLabel",
  "rateType",
  "containerTypeId",
  "requiredRole",
] as const;

const SUBTITLE_KEY_PRIORITY = [
  "code",
  "stepOrder",
  "currency",
  "tradeDirection",
  "requiredRole",
] as const;

export interface RuleEngineCardPresentation {
  titleKey: string;
  subtitleKey?: string;
  codeKey?: string;
  statusKey?: string;
  detailColumns: ResourceColumn[];
}

export const resolveCardPresentation = (
  config: RuleEngineResourceConfig,
): RuleEngineCardPresentation => {
  const titleKey =
    config.cardTitleKey ??
    TITLE_KEY_PRIORITY.find((key) =>
      config.columns.some((col) => col.accessorKey === key),
    ) ??
    config.columns.find((col) => col.format !== "code" && col.accessorKey !== "isActive")
      ?.accessorKey ??
    "id";

  const codeKey =
    config.cardCodeKey ??
    config.columns.find((col) => col.format === "code")?.accessorKey;

  const statusKey = config.columns.find((col) => col.format === "activeBadge")?.accessorKey;

  const subtitleKey =
    config.cardSubtitleKey ??
    SUBTITLE_KEY_PRIORITY.find(
      (key) =>
        key !== titleKey &&
        key !== codeKey &&
        config.columns.some((col) => col.accessorKey === key),
    );

  const detailColumns = config.columns.filter((col) => {
    if (col.accessorKey === titleKey) return false;
    if (codeKey && col.accessorKey === codeKey) return false;
    if (subtitleKey && col.accessorKey === subtitleKey) return false;
    if (statusKey && col.accessorKey === statusKey) return false;
    return true;
  });

  return { titleKey, subtitleKey, codeKey, statusKey, detailColumns };
};

export const cardInitials = (title: string): string => {
  const words = title.trim().split(/\s+/).filter(Boolean);
  if (words.length === 0) return "?";
  if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
  return `${words[0][0] ?? ""}${words[1][0] ?? ""}`.toUpperCase();
};
