import usePollClosingTimes from "../../../hooks/election/usePollClosingTimes/index.js";
import { useNowInterval } from "../../../hooks/time/index.js";
import StateBlocks from './StateBlocks';
import TimeStamp from './TimeStamp';
import ClosedDetailedText from './ClosedDetailedText';

/**
 * 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 PollsClosingGlimpse = function PollsClosingGlimpse() {
  const currentTime = useNowInterval(60000);
  const pollClosingTimes = usePollClosingTimes();
  const mostRecentEvent = 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 (aDelta > bDelta) return a;
    return b;
  }, undefined);
  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 showTimeStamp = event => event.partiallyClosed.length > 0 || event.fullyClosed.length > 0;
  return <div>

      {mostRecentEvent && <div>
          {showTimeStamp(mostRecentEvent) && <TimeStamp eventTime={new Date(mostRecentEvent.date)} />}

          <StateBlocks partiallyClosed={mostRecentEvent.partiallyClosed} fullyClosed={mostRecentEvent.fullyClosed} />

          <ClosedDetailedText partiallyClosed={mostRecentEvent.partiallyClosed} pastEvent />
        </div>}

      {nextEvent && <div>
          {showTimeStamp(nextEvent) && <TimeStamp eventTime={new Date(nextEvent.date)} />}

          <StateBlocks closingSoon={[...nextEvent.fullyClosed, ...nextEvent.partiallyClosed]} />

          <ClosedDetailedText partiallyClosed={nextEvent.partiallyClosed} />
        </div>}

    </div>;
};
PollsClosingGlimpse.defaultProps = {};
PollsClosingGlimpse.propTypes = {};
export default PollsClosingGlimpse;