import { parse, parseISO, isValid } from "date-fns";
import * as XLSX from "xlsx";

const DATE_PATTERNS = [
  "d MMM yyyy HH:mm",
  "d MMM yyyy H:mm",
  "dd MMM yyyy HH:mm",
  "dd MMM yyyy H:mm",
  "yyyy-MM-dd HH:mm:ss",
  "yyyy-MM-dd",
  "MM/dd/yyyy HH:mm",
  "MM/dd/yyyy",
];

export function parseUnknownDate(raw: unknown): string | null {
  if (!raw && raw !== 0) return null;

  if (raw instanceof Date) {
    return isValid(raw) ? raw.toISOString() : null;
  }

  if (typeof raw === "number") {
    const parsed = XLSX.SSF.parse_date_code(raw);
    if (!parsed) return null;

    const date = new Date(
      Date.UTC(parsed.y, parsed.m - 1, parsed.d, parsed.H, parsed.M, parsed.S),
    );
    return isValid(date) ? date.toISOString() : null;
  }

  if (typeof raw !== "string") return null;
  const trimmed = raw.trim();
  if (!trimmed) return null;

  const isoDate = parseISO(trimmed);
  if (isValid(isoDate)) return isoDate.toISOString();

  for (const pattern of DATE_PATTERNS) {
    const parsed = parse(trimmed, pattern, new Date());
    if (isValid(parsed)) return parsed.toISOString();
  }

  const fallback = new Date(trimmed);
  return isValid(fallback) ? fallback.toISOString() : null;
}

export function monthLabel(isoDate: string) {
  const date = parseISO(isoDate);
  return new Intl.DateTimeFormat("en-GB", {
    month: "short",
    year: "numeric",
  }).format(date);
}
