/* eslint-disable react/no-array-index-key */
import { useCallback, useRef } from 'react';
import get from 'lodash/get';
import cx from "../../../utils/css/cx.js";
import getColor from "../../../utils/colors/getColor.js";
import OutlineFilter from "../../decoration/OutlineFilter/index.js";
import { usePlot } from "../../../hooks/visualization/index.js";
import Canvas from 'Components/Canvas';
import drawFrame from './drawFrame';
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const Scatterplot = function Scatterplot(props) {
  const {
    dataset,
    title,
    plot: plotConfig,
    marginPx = 20,
    drawFrame: frameCb = drawFrame,
    isAnimated
  } = props;
  const state = useRef([]);
  const plot = usePlot({
    type: 'scatter',
    dataset,
    config: plotConfig
  });
  const hasAxes = get(plot, 'config.axes', true);
  const drawCanvasFrame = useCallback(({
    canvas,
    dt
  }) => frameCb({
    canvas,
    plot,
    dt,
    marginPx,
    state: state.current
  }), [plot, marginPx]);
  return <div className={cls('canvas', {
    noAxes: !hasAxes
  })} style={{
    '--margin': marginPx
  }}>
      {title && <h2 className={cls('title')}>
          {title}
        </h2>}

      <div className={classes.chart}>
        <Canvas drawFrame={drawCanvasFrame} isAnimated={isAnimated} />
      </div>

      {hasAxes && <>
          {plot && <div className={classes.xlabel}>
              {plot.config.xaxis}
            </div>}

          {plot && <div className={classes.xaxis}>
              {plot.scales.x.ticks(4).map(tick => <div key={tick} className={classes.xaxisTick} style={{
          '--x': plot.scales.x(tick)
        }}>
                  {tick}
                </div>)}
            </div>}

          {plot && <div className={classes.ylabel}>
              {plot.config.yaxis}
            </div>}

          {plot && <div className={classes.yaxis}>
              {plot.scales.y.ticks(4).map(tick => <div key={tick} className={classes.yaxisTick} style={{
          '--y': plot.scales.y(tick)
        }}>
                  {tick}
                </div>)}
            </div>}
        </>}

      <div className={classes.annotations}>
        {get(plot, 'config.annotations', []).map((annotation, i) => <div key={i} className={cls('text', annotation.justify)} style={{
        '--x': plot.scales.x(annotation.x),
        '--y': plot.scales.y(annotation.y),
        '--rotate': annotation.rotate,
        '--color': getColor(annotation.color)
      }}>
            <OutlineFilter radius="2" bg="warmgray-10">
              {annotation.text}
            </OutlineFilter>
          </div>)}
      </div>
    </div>;
};
export default Scatterplot;