import { storage } from "@/configs/storage";
import dayjs from "dayjs";

/**
 * Format phone number to international format
 */
export const formatePhoneNumber = (phone: string | undefined | null) => {
  if (!phone) return "";
  if (phone.startsWith("+")) return phone;
  return `+${phone?.trim()}`;
};

/**
 * Get email or phone number based on type
 */
export const emailOrPhone = (value: string, isEmail: boolean) => {
  const type = isEmail ? "email" : "phone";
  return { type, [type]: isEmail ? value : formatePhoneNumber(value) };
};

export const secondToTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};

export const formatDate = async (date: string | Date | dayjs.Dayjs, locale?: string) => {
  if (!date) return "";

  const lang = locale || (typeof window !== "undefined" ? JSON.parse(storage.getString("language") || '{"code":"en"}').code : "en");

  const d = dayjs(date).locale(lang);

  const day = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("DD")));
  const month = d.format("MMM"); // month name is already localized by dayjs
  const year = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("YYYY")));

  return `${day} ${month} ${year}`;
};

export const formatBalance = (balance: number) => {
  if (balance >= 1000000) {
    const millions = (balance / 1000000).toFixed(1).replace(/\.0$/, "");
    return `${millions}M`;
  }
  return balance?.toFixed(2);
};

export const isImage = (url: string): boolean => {
  const cleaned = url.split("?")[0];
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(cleaned);
};

export const formatDateTime = (date: string | Date | dayjs.Dayjs, locale?: string) => {
  if (!date) return "";

  const lang = "en";

  const d = dayjs(date).locale(lang);

  const day = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("DD")));
  const month = d.format("MMM");
  const year = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("YYYY")));
  const hour = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("hh")));
  const minute = new Intl.NumberFormat(lang, { useGrouping: false }).format(Number(d.format("mm")));
  const ampm = d.format("A"); // AM/PM

  return `${day} ${month} ${year}, ${hour}:${minute} ${ampm}`;
};
