import { useCalendar } from "../../../hooks/election/index.js";
import cx from "../../../utils/css/cx.js";
import PropTypes from "../../../utils/prop-types/index.js";
import { useMemo, useState } from 'react';
import groupToMap from "../../../utils/grouping/groupToMap.js";
import { useNowInterval } from "../../../hooks/time/index.js";
import useDateFormat from "../../../hooks/useDateFormat/index.js";
import classes from './styles.module.scss';
import getMonths from './utils/getMonths';
import CardItem from './CardItem';
const cls = cx.merge(classes);

/**
 * Stack of calendar months showing election contest dates
 */
function PrimaryCalCardStack(props) {
  const {
    demConventionReporterNote,
    gopConventionReporterNote
  } = props;
  const calData = useCalendar();
  const [fullCard, setFullCard] = useState();

  // Updates every five minutes
  const now = useNowInterval(300000);
  const activeMonth = useDateFormat(now, {
    format: '{m}',
    timeZone: 'UTC'
  });
  const activeYear = useDateFormat(now, {
    format: '{Y}',
    timeZone: 'UTC'
  });
  const dataByMonth = useMemo(() => {
    if (!calData) return undefined;
    const {
      electionEvents = [],
      partyConventions = [],
      namedElections = []
    } = calData;

    // Primary elections by month
    const eventsMap = groupToMap(electionEvents, 'date', {
      // Group by month
      converter: string => string.slice(5, 7)
    });

    // Party conventions by month
    const consMap = groupToMap(partyConventions, 'startDate', {
      converter: string => string.slice(5, 7)
    });

    // Named elections by month
    const namedMap = groupToMap(namedElections, 'date', {
      // Group by month
      converter: string => string.slice(5, 7)
    });
    return {
      eventsMap,
      consMap,
      namedMap
    };
  }, [calData]);
  if (!calData) return null;
  const isPostElex = !dataByMonth.eventsMap.has(activeMonth);
  const isActiveCycle = activeYear === calData.cycleMetadata.cycle;
  const months = getMonths();
  return <div className={cls('stack-container', {
    'post-elex': isPostElex
  })}>
      {months.map(({
      name,
      num
    }, i, ms) => <CardItem key={`${name}-${num}`} monthMeta={{
      name,
      num
    }} monthData={dataByMonth?.eventsMap.get(num)} convention={dataByMonth?.consMap.get(num)} namedElex={dataByMonth?.namedMap.get(num)} activeMonth={isActiveCycle && activeMonth} fullCard={fullCard} setFullCard={setFullCard} conventionNotes={{
      demConventionReporterNote,
      gopConventionReporterNote
    }} isLast={i === ms.length - 1} />)}
    </div>;
}
PrimaryCalCardStack.defaultProps = {
  demConventionReporterNote: undefined,
  gopConventionReporterNote: undefined
};
PrimaryCalCardStack.propTypes = {
  /**
   * Dem convention reporter note
   */
  demConventionReporterNote: PropTypes.object,
  /**
   * GOP convention reporter note
   */
  gopConventionReporterNote: PropTypes.object
};
export default PrimaryCalCardStack;