import { useMemo } from 'react';
import cx from "../../../../utils/css/cx.js";
import { IfActive } from "../../../application/index.js";
import HeadingThreshold from './HeadingThreshold';
import HeadingDelegates from './HeadingDelegates';
import DelegateRow from './DelegateRow';
import ExpandRow from './ExpandRow';
import CandidatesNote from './CandidatesNote';
import useDisplayCandidates from './useDisplayCandidates';
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const DelegateTable = function DelegateTable(props) {
  const {
    delegates,
    candidates,
    componentWidth,
    displayCandidates,
    displayCandidatesNumber
  } = props;
  const {
    threshold,
    total
  } = delegates;
  const [anyMetThreshold, highestCandidateTotal] = useMemo(() => {
    let amt = false;
    let hct = 0;
    candidates.forEach(c => {
      if (!amt && c.total >= threshold) {
        amt = true;
      }
      hct = Math.max(hct, c.total);
    });
    return [amt, hct];
  }, [candidates, threshold]);
  const {
    showCandidates,
    hideCandidates,
    isExpanded,
    setIsExpanded
  } = useDisplayCandidates({
    candidates,
    displayCandidates,
    displayCandidatesNumber
  });
  const showToggle = displayCandidates === 'expand';
  return <div>
      <div role="table" className={cls('delegate-table')}>
        <div role="rowgroup">
          <div role="row">
            <div role="columnheader" aria-label="Candidate Name" />
            <HeadingDelegates />
            <HeadingThreshold threshold={threshold} anyMetThreshold={anyMetThreshold} />
          </div>
        </div>
        <div role="rowgroup">
          {showCandidates.map((candidate, idx) => <DelegateRow key={candidate.id} idx={idx} threshold={threshold} anyMetThreshold={anyMetThreshold} highestCandidateTotal={highestCandidateTotal} totalDelegates={total} componentWidth={componentWidth} {...candidate} />)}

          <IfActive active={showToggle}>
            <ExpandRow isExpanded={isExpanded} setIsExpanded={setIsExpanded} />
          </IfActive>
        </div>
      </div>
      <IfActive active={displayCandidates === 'note'}>
        <CandidatesNote candidates={hideCandidates} />
      </IfActive>
    </div>;
};
export default DelegateTable;