import PropTypes from 'prop-types';
import { useModuleLastUpdated, usePageUpdateTime, usePageBuildTime, useElectionTimestampFormat } from "../../../hooks/election/index.js";
import { useFormattedTimestamp } from "../../../hooks/time/index.js";
import { capfirst } from 'journalize';
import useIsMounted from "../../../hooks/useIsMounted/index.js";
import useDateFormat from "../../../hooks/useDateFormat/index.js";
import classes from './styles.module.scss';

/**
 * The last-updated timestamp of a module or page.
 */
const ModuleLastUpdated = function ModuleLastUpdated(props) {
  const {
    scope,
    format
  } = props;
  const isMounted = useIsMounted();
  const timestampFormat = useElectionTimestampFormat();
  const moduleTime = useModuleLastUpdated();
  const pageTime = usePageUpdateTime();
  const buildTime = usePageBuildTime();
  const timestamps = {
    module: moduleTime,
    page: pageTime
  };
  const timestamp = timestamps[scope] || buildTime;
  const ssrFormatted = useDateFormat(buildTime, {
    timeZone: 'America/New_York'
  });
  const clientFormatted = useFormattedTimestamp(timestamp, {
    format: timestampFormat
  });
  const formatted = isMounted ? clientFormatted : ssrFormatted;
  const iso = useDateFormat(timestamp, {
    format: 'iso'
  });
  const Tag = scope === 'page' ? 'time' : 'div';
  const text = `${format === 'short' ? '' : 'updated '}${formatted}`;
  return <Tag className={classes.timestamp} dateTime={iso}>
      {capfirst(text)}
    </Tag>;
};
ModuleLastUpdated.defaultProps = {
  scope: 'module',
  format: 'full'
};
ModuleLastUpdated.propTypes = {
  /**
   * Specify the scope of the timestamp you want to use. A `module` scope uses
   * the last-updated time within the context of the containing module while
   * a `page` scope uses the last-updated time of the page as a whole.
   */
  scope: PropTypes.oneOf(['module', 'page']),
  /**
   * Specify the format of the timestamp you want to use
   */
  format: PropTypes.oneOf(['full', 'short'])
};
export default ModuleLastUpdated;