import { TFunction } from "i18next";

export function translateQcItemAllBackendMessage(
  message: string,
  t: TFunction,
): string {
  const categoryDeleteMatch = message.match(
    /Cannot delete QcCategory\. It has (\d+) item\(s\) and (\d+) qc item\(s\) linked to it\./,
  );
  if (categoryDeleteMatch) {
    return t(
      "Cannot delete QcCategory. It has {itemCount} item(s) and {qcItemCount} qc item(s) linked to it.",
    )
      .replace("{itemCount}", categoryDeleteMatch[1])
      .replace("{qcItemCount}", categoryDeleteMatch[2]);
  }

  if (
    message.includes("Cannot delete QcItem") &&
    message.includes("QcCategories")
  ) {
    return t(
      "Cannot delete QcItem. It is linked to one or more QcCategories.",
    );
  }

  if (
    message.includes("already has type") &&
    message.includes("linked to QcCategory")
  ) {
    const match = message.match(
      /type "([^"]+)" linked to QcCategory[:\s]+(.+?)(?:\.|One item)/,
    );
    const type = match?.[1] ?? "";
    const categoryName = match?.[2]?.trim() ?? "";
    return t(
      'Item already has type "{{type}}" in QcCategory "{{category}}". One item can only have each type in one QcCategory.',
      { type, category: categoryName },
    );
  }

  const zhCategoryTypeMatch = message.match(
    /物料 (.+?) 已經以 (.+?) 映射在模板 (.+?)，不能再把模板 (.+?) 改為 (.+)/,
  );
  if (zhCategoryTypeMatch) {
    return t(
      "Item {{itemCode}} is already mapped as {{type}} in category {{conflictCategory}}. Cannot set category {{currentCategory}} to {{newType}}.",
      {
        itemCode: zhCategoryTypeMatch[1],
        type: zhCategoryTypeMatch[2],
        conflictCategory: zhCategoryTypeMatch[3],
        currentCategory: zhCategoryTypeMatch[4],
        newType: zhCategoryTypeMatch[5],
      },
    );
  }

  const staticKeys = ["Code cannot be empty", "Name cannot be empty"];
  if (staticKeys.includes(message)) {
    const translated = t(message);
    if (translated !== message) {
      return translated;
    }
  }

  return message;
}

export function formatQcTypeLabel(type: string, t: TFunction): string {
  const translated = t(`Type.${type}`, { defaultValue: type });
  return translated;
}
