export const formatNumber = (val: number) => {
  return new Intl.NumberFormat("vi-VN").format(val);
};

export const formatCarriers = (text) => {
  if (!text) return "";
  return text.replace(/,\s*/g, ", ");
};

export const setWithExpiry = <T>(
  key: string,
  value: T,
  ttlMs?: number | null,
) => {
  const now = Date.now();

  const item = {
    value,
    expiry: ttlMs ? now + ttlMs : now + 60 * 60 * 1000, // Default 1 hour
  };

  localStorage.setItem(key, JSON.stringify(item));
};

export const getWithExpiry = <T>(key: string): T | null => {
  const itemStr = localStorage.getItem(key);
  if (!itemStr) return null;

  try {
    const item = JSON.parse(itemStr);

    if (!item.expiry || Date.now() > item.expiry) {
      localStorage.removeItem(key);
      return null;
    }

    return item.value as T;
  } catch {
    localStorage.removeItem(key);
    return null;
  }
};

type CurrencyCode =
  | "VND"
  | "USD"
  | "EUR"
  | "JPY"
  | "KRW"
  | "CNY"
  | "SGD"
  | "THB";

export const formatCurrency = (
  amount: number | string,
  currency?: string,
  locale?: string,
) => {
  if (amount === null || amount === undefined || amount === "") return "";

  const value = Number(amount);

  const resolvedLocale =
    locale ??
    (currency === "VND" ? "vi-VN" : currency === "USD" ? "en-US" : "en-GB");

  return new Intl.NumberFormat(resolvedLocale, {
    style: "currency",
    currency,
    minimumFractionDigits: currency === "VND" ? 0 : 2,
  }).format(value);
};

export const convertOrderStatusToText = (status: number) => {
  //   1: chờ thanh toán
  // 2: đã thanh toán, chờ xuất esim
  // 3: thanh toán thất bại
  // 4: đã trả esim
  switch (status) {
    case 1:
      return "Chờ thanh toán";
    case 2:
      return "Đã thanh toán, chờ xuất eSIM";
    case 3:
      return "Thanh toán thất bại";
    case 4:
      return "Đã trả eSIM";
    default:
      return "Không xác định";
  }
};

export const convertOrderStatusToColor = (type: number) => {
  switch (type) {
    case 1:
      return "bg-orange-400 text-white";
    case 2:
      return "bg-[#00c087] text-white";
    case 3:
      return "bg-red-400 text-white";
    case 4:
      return "bg-blue-400 text-white";
    default:
      return "bg-slate-800 text-white";
  }
};
