import { useMemo } from 'react';
import cx from "../../../../utils/css/cx.js";
import useTooltip from "../../../../hooks/useTooltip/index.js";
import sortBy from "../../../../utils/sorting/sortBy.js";
import StateBox from './StateBox';
import classes from './styles.module.scss';
import TrackerTooltip from '../TrackerTooltip';
const cls = cx.merge(classes);
export default function StatesStack({
  eventStates,
  eventCandidateTotal,
  setActiveCand,
  activeCand
}) {
  const allDelegatesAwarded = useMemo(() => {
    // Collect and flatten data by candidate or state (if empty)
    const statesMunged = eventStates.map(({
      candidates,
      stateFips,
      ...state
    }) => {
      // Get the states that don't have any delegates award yet
      const noWinners = candidates.every(({
        total
      }) => total === 0);
      if (noWinners) {
        return {
          stateFips,
          total: state.total
        };
      }

      // Get all the candidates with delegates then flatten
      const c = candidates.filter(({
        total
      }) => total > 0).map(x => {
        const [, candTotal] = eventCandidateTotal.find(([id]) => id === x.id);
        return {
          ...x,
          stateFips,
          candTotal
        };
      }).flat();
      return c;
    });
    return sortBy(statesMunged.flat(), [{
      comparison: 'candTotal',
      direction: 'desc'
    }, {
      comparison: 'id',
      direction: 'desc'
    }, {
      comparison: 'total',
      direction: 'desc'
    }, 'stateFips']);
  }, [eventStates, eventCandidateTotal]);

  // Total delegates available for the given event module
  // Used for height calculation
  const allDelegatesTotal = useMemo(() => allDelegatesAwarded.map(({
    total
  }) => total).reduce((prev, curr) => prev + curr, 0), [allDelegatesAwarded]);
  const tooltip = useTooltip({
    content: TrackerTooltip,
    props: {
      candidatesTotal: eventCandidateTotal,
      allDelegatesAwarded,
      setActiveCand
    },
    displayProps: {
      edge: 'sharp',
      shadow: '100',
      padding: '4'
    }
  });
  return <div className={cls('state-container')} style={{
    '--container-h': `${allDelegatesTotal}px`
  }}>
      {allDelegatesAwarded.map(delegate => <StateBox key={`${delegate.id || ''}${delegate.stateFips}`} delegate={delegate} tooltip={tooltip} activeCand={activeCand} />)}
    </div>;
}