import { TFunction } from "i18next";
import { ItemLotTraceQcResult } from "@/app/api/itemTracing";

const normCode = (code: string | null | undefined) => (code ?? "").trim();

const lookupCode = (t: TFunction, prefix: string, code: string | null | undefined): string => {
  const raw = normCode(code);
  if (!raw) return "—";
  const variants = [raw, raw.toUpperCase(), raw.toLowerCase()];
  for (const v of variants) {
    const key = `${prefix}.${v}`;
    const translated = t(key, { defaultValue: "" });
    if (translated && translated !== key) return translated;
  }
  return raw.replace(/_/g, " ");
};

export type TraceLabelTranslator = {
  refType: (code: string | null | undefined) => string;
  movementType: (code: string | null | undefined) => string;
  direction: (code: string | null | undefined) => string;
  stockInStatus: (code: string | null | undefined) => string;
  adjustmentType: (code: string | null | undefined) => string;
  usageType: (code: string | null | undefined) => string;
  failType: (code: string | null | undefined) => string;
  productionStatus: (code: string | null | undefined) => string;
  pickStatus: (code: string | null | undefined) => string;
  processingStatus: (code: string | null | undefined) => string;
  matchStatus: (code: string | null | undefined) => string;
  lotLineStatus: (code: string | null | undefined) => string;
  joStatus: (code: string | null | undefined) => string;
  qcType: (code: string | null | undefined) => string;
  qcPassed: (passed: boolean) => string;
  putawayShelfStatus: (phase: "pending" | "completed") => string;
};

export const createTraceLabelTranslator = (t: TFunction): TraceLabelTranslator => ({
  refType: (code) => lookupCode(t, "code.refType", code),
  movementType: (code) => lookupCode(t, "code.movementType", code),
  direction: (code) => {
    const u = normCode(code).toUpperCase();
    if (u === "IN") return t("directionIn");
    if (u === "OUT") return t("directionOut");
    return lookupCode(t, "code.direction", code);
  },
  stockInStatus: (code) => lookupCode(t, "code.stockInStatus", code),
  adjustmentType: (code) => lookupCode(t, "code.adjustmentType", code),
  usageType: (code) => lookupCode(t, "code.usageType", code),
  failType: (code) => lookupCode(t, "code.failType", code),
  productionStatus: (code) => lookupCode(t, "code.productionStatus", code),
  pickStatus: (code) => lookupCode(t, "code.pickStatus", code),
  processingStatus: (code) => lookupCode(t, "code.processingStatus", code),
  matchStatus: (code) => lookupCode(t, "code.matchStatus", code),
  lotLineStatus: (code) => lookupCode(t, "code.lotLineStatus", code),
  joStatus: (code) => lookupCode(t, "code.joStatus", code),
  qcType: (code) => {
    const raw = normCode(code);
    const u = raw.toUpperCase();
    if (!raw || u === "QC") return t("code.qcType.IQC");
    return lookupCode(t, "code.qcType", code);
  },
  qcPassed: (passed) => (passed ? t("qcPassed") : t("qcFailed")),
  putawayShelfStatus: (phase) =>
    phase === "completed" ? t("putawayStatusCompleted") : t("putawayStatusPending"),
});

/** Color for 處理狀態 / 對料狀態 values on flow cards and detail panel. */
export type PickStatusValueColor = "success" | "error" | "warning" | "info" | "default";

export const pickStatusValueColor = (
  code: string | null | undefined,
): PickStatusValueColor => {
  switch (normCode(code).toLowerCase()) {
    case "completed":
      return "success";
    case "rejected":
      return "error";
    case "scanned":
      return "info";
    case "pending":
    case "created":
      return "warning";
    default:
      return "default";
  }
};

export const qcItemShortLabel = (q: ItemLotTraceQcResult): string =>
  q.qcItemName?.trim() || q.qcItemCode?.trim() || "";

export const qcItemLabel = (q: ItemLotTraceQcResult): string => {
  const name = qcItemShortLabel(q);
  const desc = q.qcItemDescription?.trim();
  if (name && desc) return `${name}（${desc}）`;
  return name || desc || "";
};

export const groupQcResultsBySession = (
  results: ItemLotTraceQcResult[],
): ItemLotTraceQcResult[][] => {
  const map = new Map<string, ItemLotTraceQcResult[]>();
  results.forEach((q) => {
    const key = `${q.stockInLineId}:${q.created ?? ""}`;
    const list = map.get(key) ?? [];
    list.push(q);
    map.set(key, list);
  });
  return Array.from(map.values());
};

export const buildQcCriteriaLines = (
  results: ItemLotTraceQcResult[],
  tr: TraceLabelTranslator,
  unknownItemLabel: string,
  failQtyLabel: string,
): string => {
  if (results.length === 0) return "—";
  return results
    .map((q) => {
      const item = qcItemLabel(q) || unknownItemLabel;
      const status = q.qcPassed
        ? tr.qcPassed(true)
        : `${tr.qcPassed(false)}${q.failQty > 0 ? `（${failQtyLabel}: ${q.failQty}）` : ""}`;
      return `${item}：${status}`;
    })
    .join("\n");
};

export const buildQcSubtitle = (
  results: ItemLotTraceQcResult[],
  formatQcSubtitle: (failQty: number, acceptedQty: number) => string,
  extra?: string,
): string => {
  const first = results[0];
  const qtyLine = first ? formatQcSubtitle(first.failQty, first.acceptedQty) : "";
  const criteria = results
    .map((q) => qcItemShortLabel(q))
    .filter(Boolean)
    .slice(0, 3)
    .join(" · ");
  const parts = [extra, criteria, qtyLine].filter(Boolean);
  return parts.join(" · ") || qtyLine || "—";
};

export type DoOutboundKindLabels = {
  extra: string;
  replenish: string;
};

/** Detail label for 加單·補貨. */
export const formatDoOutboundKindLabel = (
  isExtra?: boolean,
  isReplenish?: boolean,
  labels?: DoOutboundKindLabels,
): string | undefined => {
  if (!labels) return undefined;
  const parts: string[] = [];
  if (isExtra) parts.push(labels.extra);
  if (isReplenish) parts.push(labels.replenish);
  return parts.length > 0 ? parts.join(" · ") : undefined;
};

import {
  resolveTraceDoOutboundIsExtra,
  type TraceDoOutboundExtraSource,
} from "@/utils/traceDoOutboundExtra";

export type DoOutboundChipSource = TraceDoOutboundExtraSource & {
  isReplenish?: boolean;
};

/** Resolve chip flags from API fields, with ticket-type fallback (TI-E / TI-M rules). */
export const resolveDoOutboundChipFlags = (
  source: DoOutboundChipSource,
): { isExtra: boolean; isReplenish: boolean } => ({
  isExtra: resolveTraceDoOutboundIsExtra(source),
  isReplenish: source.isReplenish === true,
});

/**
 * FP-MTMS Version Checklist | Functions Ref. No. 23 | v1.0.0 | 2026-07-20
 * Outbound qty color (DO_OUT / JO_OUT / MATERIAL_PICK):
 * 改數 → orange; else qty > 0 → green; qty ≤ 0 → red.
 */
export const resolveDoOutboundQtyColor = (
  qty: number | null | undefined,
  qtyChanged?: boolean,
): "warning.main" | "success.main" | "error.main" | undefined => {
  if (qtyChanged) return "warning.main";
  if (qty == null || !Number.isFinite(Number(qty))) return undefined;
  return Number(qty) > 0 ? "success.main" : "error.main";
};
