import { formatNumber, type NumberLanguage } from "@/lib/number-utils";

export type UploadedFileMetadata = {
  path: string;
  name: string;
  size: number;
  mimeType: string;
};

export function isDocumentPlaceholder(value?: string | null) {
  const trimmed = value?.trim();

  if (!trimmed) return true;

  return (
    trimmed === "Not Uploaded" ||
    trimmed === "—" ||
    trimmed === "-" ||
    trimmed === "No document"
  );
}

export function getDisplayFileName(
  value?: string | null,
  fallback = "Meeting Document",
) {
  if (!value?.trim() || isDocumentPlaceholder(value)) {
    return fallback;
  }

  const valueWithoutHash = value.split("#")[0] ?? value;
  const [cleanPath, queryString = ""] = valueWithoutHash.split("?");

  const originalName = new URLSearchParams(queryString).get("originalName");

  let fileName =
    originalName?.trim() ||
    cleanPath.replace(/\\/g, "/").split("/").filter(Boolean).pop()?.trim() ||
    value.trim();

  try {
    fileName = decodeURIComponent(fileName);
  } catch {
    // Keep the raw filename when URL decoding fails.
  }

  // Examples:
  // 1784339096319-e1f5a2ce-GPSF-MIS.pdf -> GPSF-MIS.pdf
  // 1784272046478-Install_MySQL.pdf      -> Install_MySQL.pdf
  const displayName = fileName.replace(
    /^\d+-(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){0,3}-?)?/i,
    "",
  );

  return displayName || fileName;
}

// Keeps file labels short in tables and detail screens.
// The file extension stays visible, for example:
// "Very-long-report-name.pdf" -> "Very-lon...pdf".
export function truncateFileName(fileName: string, maxLength = 15): string {
  if (fileName.length <= maxLength) {
    return fileName;
  }

  const extensionIndex = fileName.lastIndexOf(".");
  const extension = extensionIndex > 0 ? fileName.slice(extensionIndex) : "";
  const ellipsis = "...";
  const availableNameLength = maxLength - extension.length - ellipsis.length;

  if (extension && availableNameLength > 0) {
    return `${fileName.slice(0, availableNameLength)}${ellipsis}${extension}`;
  }

  return `${fileName.slice(0, maxLength - ellipsis.length)}${ellipsis}`;
}

// Turns a stored backend path into a URL the browser can open.
export function getDocumentUrl(filePath: string): string {
  if (/^https?:\/\//i.test(filePath)) {
    return filePath;
  }

  const apiUrl =
    process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";
  const apiOrigin = apiUrl.replace(/\/api\/v\d+\/?$/, "").replace(/\/+$/, "");
  const path = filePath.startsWith("/") ? filePath : `/${filePath}`;

  return `${apiOrigin}${path}`;
}

// Formats stored byte values for document cards and detail screens.
export function formatFileSize(
  size?: number | null,
  language: NumberLanguage = "en",
): string {
  if (
    size === null ||
    size === undefined ||
    !Number.isFinite(size) ||
    size < 0
  ) {
    return "-";
  }

  if (size < 1024 * 1024) {
    return `${formatNumber(Math.max(1, Math.round(size / 1024)), language)} KB`;
  }

  return `${formatNumber((size / (1024 * 1024)).toFixed(1), language)} MB`;
}

export function isMeaningfulFileSize(size?: string | null) {
  const trimmed = size?.trim();

  if (!trimmed) return false;

  return !isDocumentPlaceholder(trimmed);
}

export function formatDocumentCellValue(
  value?: string | null,
  emptyLabel = "Not Uploaded",
) {
  if (isDocumentPlaceholder(value)) {
    return emptyLabel;
  }

  return getDisplayFileName(value, emptyLabel);
}
