import { useMemo, useState, useId } from 'react';
import cx from "../../../../utils/css/cx.js";
import useResizeObserver from "../../../../hooks/useResizeObserver/index.js";
import IfActive from "../../../application/IfActive/index.js";
import Axis from './Axis';
import VoteHistoryGradient from './Gradient';
import Lines from './Lines';
import Points from './Points';
import StateLabels from './StateLabels';
import Subtitle from './Subtitle';
import useChartArea from './useChartArea';
import useChartScales from './useChartScales';
import useLines from './useLines';
import useChartSizes from './useChartSizes';
import HoverLayer from './HoverLayer';
import classes from './styles.module.scss';
import SingleStateLabels from './SingleStateLabels';
const cls = cx.merge(classes);
const VoteHistoryChart = function VoteHistoryChart(props) {
  const {
    headline,
    states,
    disableYAxis,
    margins,
    range,
    singleMode
  } = props;
  const reactId = useId();
  const chartId = useMemo(() => reactId.split(':')[1], [reactId]);
  const [ref, [containerWidth]] = useResizeObserver();
  const [hover, setHover] = useState();
  const hovering = !singleMode && !!hover;
  const filteredMargins = useMemo(() => margins.filter(m => states.indexOf(m.fips) > -1), [margins, states]);
  const sizes = useChartSizes(containerWidth, singleMode);
  const area = useChartArea(sizes, disableYAxis, singleMode);
  const scales = useChartScales(area, range);
  const paths = useLines(filteredMargins, scales, range);
  return <div className={cls('vote-history-chart')} ref={ref}>
      <IfActive active={!singleMode}>
        <Subtitle headline={headline} states={states} />
      </IfActive>
      <svg width={sizes.width} height={sizes.height} className="chart">
        <g transform={`translate(${area.margin.left}, ${area.margin.top})`}>
          <Axis margins={margins} scales={scales} range={range} sizes={sizes} disableYAxis={disableYAxis} singleMode={singleMode} />
          <Lines range={range} chartId={chartId} paths={paths} scales={scales} sizes={sizes} setHover={setHover} hovering={hovering} singleMode={singleMode} />
          <Points chartId={chartId} margins={filteredMargins} scales={scales} sizes={sizes} setHover={setHover} hovering={hovering} />
          <IfActive active={!singleMode}>
            <StateLabels chartId={chartId} paths={paths} scales={scales} hovering={hovering} />
          </IfActive>
          <IfActive active={singleMode}>
            <SingleStateLabels chartId={chartId} scales={scales} margins={filteredMargins} sizes={sizes} area={area} />
          </IfActive>

          <IfActive active={hovering}>
            <HoverLayer chartId={chartId} paths={paths} sizes={sizes} margins={margins} scales={scales} singleMode={singleMode} hover={hover} />
          </IfActive>
        </g>

        <VoteHistoryGradient id={chartId} scales={scales} range={range} />
      </svg>
    </div>;
};
export default VoteHistoryChart;