import type { CalendarDate } from "@internationalized/date";

export const formatTime = (isoString: string | undefined) => {
  if (!isoString) return "N/A";
  try {
    return formatDistanceToNow(new Date(isoString), { addSuffix: true });
  } catch (e) {
    return "Invalid date";
  }
};

export function formatDuration(ms: number): string {
  const seconds = Math.floor(ms / 1000);
  if (seconds < 60) return `${seconds}s`;

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}m ${remainingSeconds}s`;
}

export function formatDateTimeFromIsoString(isoString: string): string {
  try {
    const date = new Date(isoString);
    return new Intl.DateTimeFormat("en-US", {
      dateStyle: "medium",
      timeStyle: "short",
    }).format(date);
  } catch (e) {
    return "Invalid date";
  }
}

export function getJustDateString(d: Date): string {
  return d.toISOString().split("T")[0];
}

export function formatDateTime(dateTimeStr: string) {
  const date = new Date(dateTimeStr);
  return {
    time: date.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    }),
    date: date.toLocaleDateString("en-US", {
      weekday: "short",
      day: "2-digit",
      month: "short",
    }),
  };
}

export function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString("en-US", {
    weekday: "short",
    day: "2-digit",
    month: "short",
  });
}

export function isTimestampMoreThan1MinAgo(ts: string): boolean {
  const lastPingedDate = new Date(ts);
  const now = new Date();
  const diff = now.getTime() - lastPingedDate.getTime();
  return diff > 60000;
}

export function isTimestampOlderThan(ts: string, seconds: number): boolean {
  const lastPingedDate = new Date(ts);
  const now = new Date();
  const diff = now.getTime() - lastPingedDate.getTime();
  return diff > seconds * 1000;
}

export function makeDateStringISO(ds: string): string {
  if (ds.includes("T")) {
    return `${ds.split("T")[0]}T00:00:00.000Z`;
  }
  return `${ds}T00:00:00.000Z`;
}

export function parseCalDateToDateString(v: CalendarDate) {
  let month: string | number = v.month;
  if (month < 10) {
    month = `0${month}`;
  }
  let day: string | number = v.day;
  if (day < 10) {
    day = `0${day}`;
  }
  return `${v.year}-${month}-${day}`;
}
