import sortBy from "../../../../utils/sorting/sortBy.js";
import { useNowInterval } from "../../../../hooks/time/index.js";
import { getStateName } from "../../../../utils/election/index.js";
import StateName from "../../StateName/index.js";
import CommaAnd from "../../../typography/CommaAnd/index.js";
import useDateFormat from "../../../../hooks/useDateFormat/index.js";
import ElectionCaretLink from "../../ElectionCaretLink/index.js";
import cx from "../../../../utils/css/cx.js";
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const PollsClosingEventCard = function PollsClosingEventCard(props) {
  const {
    time,
    partiallyClosed = [],
    fullyClosed = []
  } = props;
  const currentTime = useNowInterval(60000);
  const states = [...fullyClosed, ...partiallyClosed];
  const sortedStates = sortBy(states, [{
    comparison: state => getStateName(state)
  }]);
  const sortedPartiallyClosedStates = sortBy(partiallyClosed, [{
    comparison: partiallyClosedState => getStateName(partiallyClosedState)
  }]);
  const formattedTime = useDateFormat(time, {
    format: '{h:m?} {P} {Z}'
  });
  const timeDelta = currentTime - new Date(time);
  const diffMins = Math.round(timeDelta / (1000 * 60));
  const labelText = diffMins <= 1 ? 'Just closed' : 'Closed';
  const closedValue = diffMins <= 1 ? 'justClosed' : 'closed';
  return <div className={cls('cardContainer', {
    closedCard: timeDelta >= 0
  })}>

      <div className={classes.cardTop}>
        <h3 className={classes.timeStamp}>
          {formattedTime}
        </h3>

        {timeDelta >= 0 && <p className={cls('label', {
        justClosed: closedValue === 'justClosed',
        closed: closedValue === 'closed'
      })}>
            {labelText}
          </p>}
      </div>
      <hr className={classes.line} />
      <div className={classes.statesContainer}>
        {sortedStates.map(state => <div className={classes.state} key={state}>
            <ElectionCaretLink to={`state:${state}:index`} text={getStateName(state)} />
          </div>)}
      </div>

      {sortedPartiallyClosedStates.length > 0 && <p className={classes.partialClosuresText}>
          Partial closures in:
          {' '}

          <CommaAnd items={sortedPartiallyClosedStates.map(state => <span key={state}>
                <StateName format="name" stateFips={state} />
              </span>)} />
        </p>}

    </div>;
};
export default PollsClosingEventCard;