import { useMemo } from 'react';
import groupToMap from "../../../utils/grouping/groupToMap.js";
import sortBy from 'lodash/sortBy';
import useNowInterval from '../../time/useNowInterval';
import useDateFormat from '../../useDateFormat';
import useCalendar from '../useCalendar';
export default function useCalendarFilteredEvents({
  office,
  limit,
  include = ['convention', 'election'],
  filterPassedEvents = false
} = {}) {
  const data = useCalendar();
  const now = useNowInterval(3600000); // 1 hour
  const today = useDateFormat(now, {
    format: '{Y}-{m}-{d}'
  });
  return useMemo(() => {
    if (!data) return undefined;
    const {
      electionEvents,
      partyConventions
    } = data;

    // Handle office property filter
    const filteredEvents = electionEvents.filter(election => {
      if (!office) return true;
      const officeFlags = {
        president: election.includesPresident,
        senate: election.includesSenate,
        house: election.includesHouse,
        governor: election.includesGovernor,
        downBallot: !election.includesPresident
      };
      return officeFlags[office];
    });

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

    // Combine and sort into [key, value] arrays
    const all = [...elexByDate, ...conventionsByDate];
    const sorted = sortBy(all, ([key]) => key);

    // Handle date filter
    let finalArray = sorted;
    if (filterPassedEvents) {
      finalArray = sorted.filter(([d]) => d >= today);
    }

    // Handle type exclusion
    if (include) {
      finalArray = finalArray.filter(([, d]) => include.indexOf(d[0].type) > -1);
    }

    // Handle limit slicing
    if (limit) {
      finalArray = finalArray.slice(0, limit);
    }
    return finalArray;
  }, [data, today]);
}