import type {
  Certificate,
  CertificateRow,
  CertType,
  CertStatus,
  LegacyExcelCert,
} from "@/lib/api/types/certificate.types";

// ─────────────────────────────────────────────────────────────────────────────
// mapCertificateToRow — Raw Certificate → CertificateRow (table shape)
// ─────────────────────────────────────────────────────────────────────────────
export function mapCertificateToRow(
  cert: Certificate & { qrCode?: string; verification_url?: string },
  index: number,
): CertificateRow {
  return {
    sno: index + 1,
    id: cert.id,
    certificate_no: cert.certificate_no ?? "—",
    company_name: cert.company?.name ?? cert.company_name_snapshot ?? "—",
    company_id: cert.company?.id ?? 0,
    standard_name: cert.standard?.name ?? cert.standard_name ?? "—",
    standard_short: cert.standard_short ?? "—",
    cert_type: cert.cert_type,
    status: cert.status,
    issue_date: cert.issue_date,
    expire_date: cert.expire_date,
    surveillance_audit_due: (cert as any).surveillance_audit_due ?? null,
    recertification_due: (cert as any).recertification_due ?? null,
    scan_pdf_url: cert.scan_pdf_url,
    qrcode_token: cert.qrcode_token,
    fingerprint: cert.fingerprint,
    verification_domain: cert.verification_domain,
    verification_url: cert.verification_url ?? "",
    qrCode: cert.qrCode,
    created_at: cert.created_at,
    updated_at: cert.updated_at,
  };
}

export function mapCertificatesApiResponse(
  certs: (Certificate & { qrCode?: string; verification_url?: string })[],
): CertificateRow[] {
  return certs.map((c, i) => mapCertificateToRow(c, i));
}

// ─────────────────────────────────────────────────────────────────────────────
// Status + cert_type visual badge helpers
// ─────────────────────────────────────────────────────────────────────────────
export const CERT_TYPE_META: Record<
  CertType,
  { label: string; color: string; bg: string }
> = {
  INITIAL: { label: "Initial", color: "#15803d", bg: "#dcfce7" },
  SURVEILLANCE: { label: "Surveillance", color: "#b45309", bg: "#fef3c7" },
  RECERTIFICATION: {
    label: "Recertification",
    color: "#6d28d9",
    bg: "#ede9fe",
  },
};

export const STATUS_META: Record<
  CertStatus,
  { label: string; color: string; bg: string }
> = {
  pending_scan: { label: "Pending Scan", color: "#92400e", bg: "#fef3c7" },
  active: { label: "Active", color: "#166534", bg: "#dcfce7" },
  superseded: { label: "Superseded", color: "#475569", bg: "#f1f5f9" },
  expired: { label: "Expired", color: "#991b1b", bg: "#fef2f2" },
  revoked: { label: "Revoked", color: "#ffffff", bg: "#dc2626" },
  fake: { label: "Fake", color: "#ffffff", bg: "#000000" },
};

// ─────────────────────────────────────────────────────────────────────────────
// Column key → display value (used by dynamic column renderer)
// ─────────────────────────────────────────────────────────────────────────────
export function mapColumnKeyToValue(key: string, row: CertificateRow): any {
  const columnMap: Record<string, any> = {
    certificate_no: row.certificate_no,
    company_name: row.company_name,
    standard: row.standard_name,
    standard_short: row.standard_short,
    cert_type: row.cert_type,
    status: row.status,
    issue_date: formatDate(row.issue_date),
    expire_date: formatDate(row.expire_date),
    surveillance_audit_due: formatDate(row.surveillance_audit_due),
    recertification_due: formatDate(row.recertification_due),
    created_at: formatDate(row.created_at),
    updated_at: formatDate(row.updated_at),
  };
  return columnMap[key] ?? row[key] ?? "—";
}

function formatDate(s?: string | null) {
  if (!s) return "—";
  try {
    return new Date(s)
      .toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
      .replace(/ /g, "-");
  } catch {
    return "—";
  }
}

// ─────────────────────────────────────────────────────────────────────────────
// Export formatter — flat object for Excel/CSV
// ─────────────────────────────────────────────────────────────────────────────
export function formatCertificateForExport(
  row: CertificateRow,
): Record<string, string | number> {
  return {
    "No.": row.sno,
    "Certificate No": row.certificate_no,
    Company: row.company_name,
    Standard: row.standard_name,
    Type: CERT_TYPE_META[row.cert_type]?.label ?? row.cert_type,
    Status: STATUS_META[row.status]?.label ?? row.status,
    "Issue Date": formatDate(row.issue_date),
    "Expire Date": formatDate(row.expire_date),
    "Surv. Audit On/Before": formatDate(row.surveillance_audit_due),
    "Re-certification Due": formatDate(row.recertification_due),
    "Has Scan": row.scan_pdf_url ? "Yes" : "No",
    "Verification URL": row.verification_url,
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// Legacy helpers — parse "IMS" standard to list of short codes
// Mirrors backend logic in certificates.service.ts
// ─────────────────────────────────────────────────────────────────────────────
export function expandLegacyStandardLabel(label: string): string[] {
  const parts = label.split(",").map((s) => s.trim().toUpperCase());
  const out: string[] = [];
  parts.forEach((p) => {
    if (p === "IMS") out.push("QMS", "EMS", "OHA");
    else if (p === "QMS" || p === "ISO 9001") out.push("QMS");
    else if (p === "EMS" || p === "ISO 14001") out.push("EMS");
    else if (p === "OHA" || p === "ISO 45001") out.push("OHA");
    else if (p === "HACCP" || p === "ISO 22000") out.push("HACCP");
    else out.push(p);
  });
  return out;
}

export function parseLegacyCertNo(certNo: string): string[] {
  const parts = certNo.split(",").map((s) => s.trim());
  let pfx = "";
  return parts.map((p) => {
    if (p.includes("-")) {
      pfx = p.split("-")[0];
      return p;
    }
    return pfx + "-" + p;
  });
}

/**
 * Build a map of standard_short → legacy cert_no for a company.
 * e.g. IMS,HACCP with cert_no "ADU-2687,5985,4271,NQU-60132" →
 * { QMS: "ADU-2687", EMS: "ADU-5985", OHA: "ADU-4271", HACCP: "NQU-60132" }
 */
export function buildLegacyMap(
  legacyCerts: LegacyExcelCert[],
): Record<string, { cert_no: string; legacy_id: number }> {
  const map: Record<string, { cert_no: string; legacy_id: number }> = {};
  if (!legacyCerts?.length) return map;

  for (const legacy of legacyCerts) {
    const expanded = expandLegacyStandardLabel(legacy.standard ?? "");
    const numbers = parseLegacyCertNo(legacy.cert_no ?? "");
    expanded.forEach((short, i) => {
      if (numbers[i] && !map[short]) {
        map[short] = { cert_no: numbers[i], legacy_id: legacy.id };
      }
    });
  }
  return map;
}
