import { format, parseISO } from "date-fns";
import { keepDigits } from "./digitEntry";

/**
 * Turn whatever the user has typed into `dd-MM-yyyy`, inserting the dashes as
 * they go and ignoring everything that is not a digit.
 *
 * Extracted so the keyboard-entry rules can be tested without a DOM, and
 * shared: `DateField` and `BirthDateField` each had their own copy of this
 * function, identical apart from brace style, plus their own copy of the
 * rollover check below.
 */
export function formatDateInput(input: string): string {
  // Arabic-Indic digits from an Arabic keyboard count as digits too.
  const digitsOnly = keepDigits(input);
  if (!digitsOnly) return "";

  if (digitsOnly.length <= 2) {
    return digitsOnly;
  } else if (digitsOnly.length <= 4) {
    return `${digitsOnly.slice(0, 2)}-${digitsOnly.slice(2)}`;
  } else {
    return `${digitsOnly.slice(0, 2)}-${digitsOnly.slice(
      2,
      4
    )}-${digitsOnly.slice(4, 8)}`;
  }
}

/**
 * Whether the calendar greys out `day`.
 *
 * The floor is `enforceStartDate`, else the caller's `minDate` (the date forms
 * pass Kuwait's calendar day, `kuwaitDatePickerMinimum()`), else today. It used
 * to ignore `minDate` and floor at the browser's own today, so a visitor east
 * of Kuwait after midnight local time could not pick Kuwait's today even though
 * the form's validation accepts it. Every date is cloned: the old version ran
 * `setHours` on the caller's `enforceStartDate` object itself.
 *
 * A saved date before the floor stays enabled, so editing an old record does
 * not reject its own value; every other day before the floor is disabled.
 */
export function isCalendarDayDisabled(
  day: Date,
  {
    enforceStartDate,
    minDate,
    selected,
    now = new Date(),
  }: { enforceStartDate?: Date; minDate?: Date; selected?: Date | null; now?: Date }
): boolean {
  const midnight = (date: Date) => {
    const copy = new Date(date);
    copy.setHours(0, 0, 0, 0);
    return copy.getTime();
  };
  const floor = midnight(enforceStartDate ?? minDate ?? now);
  const thisDay = midnight(day);
  if (thisDay >= floor) return false;
  return !(selected && !isNaN(selected.getTime()) && midnight(selected) === thisDay);
}

/** A complete `dd-MM-yyyy` string, as opposed to one still being typed. */
export const COMPLETE_DATE = /^\d{2}-\d{2}-\d{4}$/;

/**
 * Parse a completed `dd-MM-yyyy` string, or `null` if it is not a real date.
 *
 * The round-trip comparison is what rejects `31-02-2024`: `new Date(2024, 1, 31)`
 * rolls forward to 2 March rather than failing, so the only way to know the
 * input was invalid is to read the fields back.
 */
export function parseTypedDate(formatted: string): Date | null {
  if (!COMPLETE_DATE.test(formatted)) return null;

  const [day, month, year] = formatted.split("-").map(Number);
  const date = new Date(year, month - 1, day);
  const rolledOver =
    date.getDate() !== day ||
    date.getMonth() !== month - 1 ||
    date.getFullYear() !== year;

  return rolledOver ? null : date;
}

/**
 * How a chosen date is written into Formik.
 *
 * `dob` is a calendar day the backend stores as `yyyy-MM-dd`; every other field
 * on this component is a timestamp. The distinction is by field name because
 * that is how the component has always made it — it is not a new rule.
 */
export function serializeSelectedDate(name: string, date: Date): string {
  return name === "dob" ? format(date, "yyyy-MM-dd") : date.toISOString();
}

/**
 * The inverse of `serializeSelectedDate`: what a stored value looks like in the
 * text box.
 *
 * Returns `""` for an empty, unparseable or invalid value, which is what the
 * three call sites each did with their own try/catch. Pulled out so the
 * stored-to-display direction can be computed during render rather than
 * assigned from an effect — the effect version painted the previous value for
 * one frame on every change.
 */
export function displayDateValue(stored: string | null | undefined): string {
  if (!stored) return "";
  try {
    const date = parseISO(stored);
    if (isNaN(date.getTime())) return "";
    return format(date, "dd-MM-yyyy");
  } catch {
    return "";
  }
}

/** Keep incomplete/invalid keyboard edits in Formik so an old saved DOB cannot be submitted. */
export function birthDateInputValue(input: string): { display: string; value: string } {
  const display = formatDateInput(input);
  const parsed = parseTypedDate(display);
  return { display, value: parsed ? serializeSelectedDate("dob", parsed) : display };
}
