import { format, isSameWeek } from "date-fns";

/** Formats a date input to a time string in "HH:mm" format. Returns an empty string if input is null or undefined. */
export const formatTime = (dateInput: string | Date | null | undefined) => {
  if (!dateInput) return "";

  const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;

  return format(date, "HH:mm");
};

/** Formats a date input to a time string in "HH:mm:ss" format. Returns an empty string if input is null or undefined. */
export const formatTimeWithSeconds = (
  dateInput: string | Date | null | undefined,
) => {
  if (!dateInput) return "";

  const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;

  return format(date, "HH:mm:ss");
};

/** Formats a date input to a human-readable date string.
 * Returns "Today" or "Tomorrow" for those respective days,
 * the weekday name (e.g. "Monday") if the date falls within the current week,
 * or "MM/dd" otherwise. Returns an empty string if input is null or undefined. */
export const formatDate = (dateInput: string | Date | null | undefined) => {
  if (!dateInput) return "";

  const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
  const now = new Date();

  if (
    date.getDate() === now.getDate() &&
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear()
  ) {
    return "Today";
  }

  const tomorrow = new Date(now);
  tomorrow.setDate(now.getDate() + 1);
  if (
    date.getDate() === tomorrow.getDate() &&
    date.getMonth() === tomorrow.getMonth() &&
    date.getFullYear() === tomorrow.getFullYear()
  ) {
    return "Tomorrow";
  }

  if (isSameWeek(date, now, { weekStartsOn: 1 })) {
    return format(date, "EEEE");
  }

  return format(date, "MM/dd");
};

/** Formats a date input to a "MM/dd/yyyy" string. Returns an empty string if input is null or undefined. */
export const formatDateMDY = (dateInput: string | Date | null | undefined) => {
  if (!dateInput) return "";

  const date = typeof dateInput === "string" ? new Date(dateInput) : dateInput;

  return format(date, "MM/dd/yyyy");
};
