import { useMemo } from 'react';
import flatten from 'lodash/flatten';
import { getContestMargins } from '../../../utils/election';
const SINGLE_MODE_BUFFER = 1;
export default function useChartProps({
  voteHistory,
  inputGroups,
  singleStateFips,
  contests,
  office,
  includeCurrentYear
}) {
  const [groups, singleMode] = useMemo(() => {
    if (inputGroups) {
      return [inputGroups, false];
    }
    if (singleStateFips) {
      return [[{
        states: [singleStateFips]
      }], true];
    }
    return [];
  }, [inputGroups, singleStateFips]);
  const [margins, range] = useMemo(() => {
    if (!voteHistory || !groups) {
      return [];
    }
    const states = flatten(groups.map(g => g.states));
    let voteMargins = voteHistory.filter(v => states.indexOf(v.state) > -1).map(v => ({
      fips: v.state,
      value: v.gopMargin * 100,
      year: v.year,
      party: v.party
    }));
    if (contests && includeCurrentYear) {
      const currentYearMargins = states.map(fips => {
        const contest = Object.entries(contests).find(([, contestData]) => {
          const metadata = contestData.combinedMetadata.contest;
          return metadata.office === office && metadata.stateFips === fips;
        });
        if (!contest) {
          return undefined;
        }
        const margin = getContestMargins('current', contest[1]);
        return {
          fips,
          year: 2024,
          value: margin.gopMargin * 100,
          party: margin.party,
          margin
        };
      });
      voteMargins = [...voteMargins, ...currentYearMargins.filter(m => !!m)];
    }
    let maxX;
    let minX;
    if (singleMode) {
      maxX = Math.max(...voteMargins.map(d => d.value)) + SINGLE_MODE_BUFFER;
      minX = Math.min(...voteMargins.map(d => d.value)) - SINGLE_MODE_BUFFER;
      if (maxX > 0 && minX < 0) {
        maxX = Math.max(maxX, -1 * minX);
        minX = Math.min(minX, -1 * maxX);
      }
    } else {
      const maxValue = Math.max(...voteMargins.map(d => Math.abs(d.value)));
      const maxValueFives = Math.floor(maxValue / 5);
      const maxNoBuffer = (maxValueFives + 1) * 5;
      maxX = maxNoBuffer > maxValue + 2 ? maxNoBuffer : maxNoBuffer + 5;
      minX = maxX * -1;
    }
    const maxYear = 2024;
    const minYear = Math.min(...voteMargins.map(d => d.year));
    const penultimateYear = Math.max(...voteMargins.map(d => d.year).filter(d => d !== maxYear));
    const rangeConfig = {
      x: {
        max: maxX,
        min: minX
      },
      y: {
        min: minYear,
        max: maxYear,
        penultimate: penultimateYear
      }
    };
    return [voteMargins, rangeConfig];
  }, [voteHistory, groups, singleMode, contests, office, includeCurrentYear]);
  return {
    groups,
    singleMode,
    margins,
    range
  };
}