import { isValid, parse } from "date-fns";

export function localDateTimeToUtcIso(
  date: string | Date | null | undefined,
  time?: string | null,
): string | undefined {
  if (!date) return undefined;

  let localDate: Date | null = null;

  if (date instanceof Date) {
    localDate = new Date(date);
  } else if (typeof date === "string") {
    // Parse the date (assuming YYYY-MM-DD format)
    const [year, month, day] = date.split("-").map(Number);
    localDate = new Date(year, month - 1, day);
  }

  if (!localDate || !isValid(localDate)) return undefined;

  if (time) {
    let hours = 0,
      minutes = 0;
    const timeMatch = time.match(/(\d+):(\d+)\s*(AM|PM)?/i);

    if (timeMatch) {
      hours = parseInt(timeMatch[1], 10);
      minutes = parseInt(timeMatch[2], 10);

      const period = timeMatch[3]?.toUpperCase();
      if (period === "PM" && hours < 12) hours += 12;
      if (period === "AM" && hours === 12) hours = 0;
    } else {
      const [h, m] = time.split(":").map(Number);
      if (!isNaN(h)) hours = h;
      if (!isNaN(m)) minutes = m;
    }

    localDate.setHours(hours, minutes, 0, 0);
  }

  return localDate.toISOString();
}
