export const BUSINESS_TIME_ZONE = "America/New_York";

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

export function currency(value: number | string | null | undefined) {
  const amount = Number(value ?? 0);
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
}

function dateParts(value: Date | string | null | undefined) {
  if (!value) return null;
  if (typeof value === "string") {
    const datePart = value.slice(0, 10);
    if (/^\d{4}-\d{2}-\d{2}$/.test(datePart)) {
      const [year, month, day] = datePart.split("-").map(Number);
      if (year && month >= 1 && month <= 12 && day >= 1 && day <= 31) return { year, month, day };
    }
    return null;
  }
  if (value instanceof Date && !Number.isNaN(value.getTime())) {
    return {
      year: value.getFullYear(),
      month: value.getMonth() + 1,
      day: value.getDate()
    };
  }
  return null;
}

export function formatDateOnly(value: Date | string | null | undefined, emptyValue = "—") {
  const parts = dateParts(value);
  if (!parts) return emptyValue;
  return `${monthNames[parts.month - 1]} ${parts.day}, ${parts.year}`;
}

export function formatDateOnlyIso(value: Date | string | null | undefined, emptyValue = "") {
  const parts = dateParts(value);
  if (!parts) return emptyValue;
  return `${parts.year}-${String(parts.month).padStart(2, "0")}-${String(parts.day).padStart(2, "0")}`;
}

export function formatDateTimeInBusinessTimezone(value: Date | string | null | undefined, emptyValue = "—") {
  if (!value) return emptyValue;
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return emptyValue;
  return new Intl.DateTimeFormat("en-US", {
    timeZone: BUSINESS_TIME_ZONE,
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
    timeZoneName: "short"
  }).format(date);
}

export function shortDate(value: Date | string | null | undefined) {
  return formatDateOnly(value, "-");
}

export function monthLabel(value: Date | string | null | undefined) {
  if (!value) return "-";
  const parts = dateParts(value);
  return parts ? `${monthNames[parts.month - 1]} ${parts.year}` : "-";
}

export function dateInput(value: Date | string | null | undefined) {
  return formatDateOnlyIso(value, "");
}

export function monthInput(value: Date | string | null | undefined) {
  if (!value) return "";
  const parts = dateParts(value);
  if (!parts) return "";
  return `${parts.year}-${String(parts.month).padStart(2, "0")}`;
}
