import PropTypes from 'prop-types';
import usePollClosingTimes from "../../../hooks/election/usePollClosingTimes/index.js";
import { useNowInterval } from "../../../hooks/time/index.js";
import ModuleTitle from '../ModuleTitle';
import PollsClosingGlimpse from '../PollsClosingGlimpse';

/**
 * This is a component that shows where and when polls are closing. Specifically, it shows where polls partially or fully closed most recently and the soonest upcoming batch of states where they will partially or fully close. The component will render this information by comparing time stamps from a dataset containing poll closing times data and comparing it to the current time. This is a recirculation module intended to be placed on index pages.
 */
const PollsClosingRecirc = function PollsClosingRecirc(props) {
  const {
    headline,
    eyebrow,
    reporterNote
  } = props;
  const currentTime = useNowInterval(60000);
  const pollClosingTimes = usePollClosingTimes();
  const nextEvent = pollClosingTimes.filter(x => currentTime < new Date(x.date)).reduce((a, b) => {
    if (!a) return b;
    const aDelta = new Date(a.date) - currentTime;
    const bDelta = new Date(b.date) - currentTime;
    if (bDelta > aDelta) return a;
    return b;
  }, undefined);
  const defaultHeadline = nextEvent ? 'Where are polls closing next?' : 'All polls have closed';
  return <div>
      <ModuleTitle headline={headline || defaultHeadline} eyebrow={eyebrow} reporterNote={reporterNote} />

      <PollsClosingGlimpse />

    </div>;
};
PollsClosingRecirc.defaultProps = {
  headline: undefined,
  eyebrow: {
    isLive: true,
    text: 'Polls closing'
  },
  reporterNote: undefined
};
PollsClosingRecirc.propTypes = {
  /**
   * The headline of module.
   */
  headline: PropTypes.string,
  /**
   * The content for the eyebrow of the module.
   */
  eyebrow: PropTypes.shape({}),
  /**
   * The contents of the reporter comment to include in the module.
   */
  reporterNote: PropTypes.shape({})
};
export default PollsClosingRecirc;