import sortBy from 'lodash/sortBy';
import { useMemo } from 'react';
import groupToMap from '../../../../utils/grouping/groupToMap.js';
const useFilteredSortedDates = function useFilteredSortedDates(opts) {
  const {
    data,
    office,
  } = opts;
  return useMemo(() => {
    if (!data) return undefined;
    const {
      electionEvents,
      partyConventions,
    } = data;

    // Handle office property filter
    let filteredEvents;
    if (office) {
      const filterFunc = ({
        officesDecided,
      }) =>
        office === 'president' ? officesDecided === 'presidentialRaceOnly' : officesDecided === 'downBallotRacesOnly';
      filteredEvents = electionEvents.filter(filterFunc);
    }

    // Normalize both datasets for sorting and grouping
    const elexByDate = groupToMap(filteredEvents || electionEvents, 'date');
    const conventionsByDate = groupToMap(partyConventions, 'startDate', {
      // Slice off time from ISO string to normalize with elections
      converter: string => string.slice(0, 10),
    });

    // Combine and sort into [key, value] array
    const all = [...elexByDate, ...conventionsByDate];
    const sorted = sortBy(all, ([key]) => key);
    return sorted;
  }, [data]);
};
export default useFilteredSortedDates;
