export const isValidDate = (d: unknown): d is Date =>
  d instanceof Date && !isNaN(d.getTime());

export const toValidDate = (
  value: Date | string | null | undefined,
): Date | null => {
  if (value == null) {
    return null;
  }
  const date = value instanceof Date ? value : new Date(value);
  return isValidDate(date) ? date : null;
};

/**
 * Bypass React's synthetic event system to set a controlled <input>'s value
 * AND fire an `input` event that React's listener picks up. Used for the
 * type-to-edit gesture: forward the keystroke that triggered edit into the
 * underlying WDS input without re-implementing its parsing.
 */
export const setNativeInputValue = (
  el: HTMLInputElement,
  value: string,
): void => {
  const setter = Object.getOwnPropertyDescriptor(
    HTMLInputElement.prototype,
    'value',
  )?.set;
  if (!setter) {
    return;
  }
  setter.call(el, value);
  el.dispatchEvent(new Event('input', { bubbles: true }));
};
