import { useMemo, useState, useEffect } from 'react';
import ensureDate from './ensureDate';
import formatDate from './formatDate';

/**
 * Hook to memoize a local time in a particular custom format that is SSR-safe.
 * The hook accepts a date-coerceable argument as well as a configuration
 * object; it returns a string of the date in the specified format. The hook
 * keeps track of when the component calling it has been mounted on the client
 * so that it can initially format the datetime in a consistent timezone before
 * localizing it dynamically on the client. That prevents hydration errors
 * caused by mismatching time formats on the server and the client. If you
 * specify a `timeZone` in the configuration object then that timezone will be
 * used throughout the lifecycle of this hook.
 *
 * You can specify a format using any of the segment identifiers listed in the
 * Custom Format story below. You can either provide the name of a single
 * segment, like `ap` (the default), or you can build your own format string
 * from multiple segments, like `{apdate} at {aptime}`.
 *
 * ```js
 *
 * import { useDateFormat } from '@politico/interactive-style';
 * ```
 *
 * @param {string|Date} date
 *   The date input to format
 * @param {Object} options
 *   Options to dictate how the formatting behaves:
 *   - `format`: how to format the date
 *   - `timeZone`: a specific timezone in which to render the datetime
 */
const useDateFormat = function useDateFormat(date, options = {}) {
  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => setIsMounted(true), []);
  const {
    format = 'ap',
    timeZone
  } = options;
  const dateKey = date && ensureDate(date).toISOString();
  return useMemo(() => formatDate(date, {
    timeZone,
    format
  }), [isMounted, dateKey, timeZone, format]);
};
export default useDateFormat;