import { useState, useMemo } from 'react';
import { useContestStatus, useCandidatesSortedByResults, useContestMetadata } from "../../../../../hooks/election/index.js";
const useGroupedCandidates = function useGroupedCandidates(id) {
  const [isExpanded, setIsExpanded] = useState(false);
  const sortedCandidates = useCandidatesSortedByResults(id);
  const contestStatus = useContestStatus(id);
  const metadata = useContestMetadata(id);
  return useMemo(() => {
    if (isExpanded === false && contestStatus.outcome === 'winner') {
      const {
        numWinners
      } = metadata;
      const cutoff = numWinners || 1;

      /**
       * If not expanded, and with a winner call
       * Show only the number of possible winners and hide the rest
       */
      return {
        candidatesToShow: sortedCandidates.slice(0, cutoff),
        otherCandidates: sortedCandidates.slice(cutoff),
        showOtherCandidatesRow: false,
        isExpanded,
        setIsExpanded
      };
    }
    if (isExpanded === false && contestStatus.outcome === 'runoff') {
      const {
        numRunoff
      } = metadata;
      const cutoff = numRunoff || 2;

      /**
       * If not expanded, and with a runoff call
       * Show only the number of possible runoff spots and hide the rest
       */

      return {
        candidatesToShow: sortedCandidates.slice(0, cutoff),
        otherCandidates: sortedCandidates.slice(cutoff),
        showOtherCandidatesRow: false,
        isExpanded,
        setIsExpanded
      };
    }
    if (isExpanded === false && sortedCandidates.length > 3) {
      /**
       * If not expanded, and no call
       * Show top two, plus aggregated other cands
       */
      return {
        candidatesToShow: sortedCandidates.slice(0, 2),
        otherCandidates: sortedCandidates.slice(2),
        showOtherCandidatesRow: true,
        isExpanded,
        setIsExpanded
      };
    }

    /**
     * Otherwise, show all candidates
     */
    return {
      candidatesToShow: sortedCandidates,
      otherCandidates: [],
      showOtherCandidatesRow: false,
      isExpanded,
      setIsExpanded
    };
  }, [isExpanded, sortedCandidates]);
};
export default useGroupedCandidates;