import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

import React from "react";
import PropTypes from "prop-types";
import { BarStack } from "@visx/shape";
import { Group } from "@visx/group";
import { AxisLeft } from "@visx/axis";
import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale";
import { useTooltip, TooltipWithBounds } from "@visx/tooltip";
import { localPoint } from "@visx/event";
import { GridRows } from "@visx/grid";
import Typography from "../Typography";
import getClasses from "./styles";
import useTheme from "../styles/useTheme";

var BarGraphMultiple = function BarGraphMultiple(props) {
  var graphData = props.graphData,
      colorArray = props.colorArray,
      colorShade = props.colorShade,
      type = props.type,
      width = props.width,
      height = props.height,
      legendVisualizer = props.legendVisualizer;
  var classes = getClasses(props);
  var categoryAPI = Object.keys(graphData[0]).shift();
  var keysToInclude = Object.keys(graphData[0]).slice(1);

  var _useTheme = useTheme(),
      _useTheme$cleverUI = _useTheme.cleverUI,
      colors = _useTheme$cleverUI.colors,
      spacing = _useTheme$cleverUI.spacing;

  var axisNum = 3;

  var _useTooltip = useTooltip(),
      tooltipData = _useTooltip.tooltipData,
      tooltipLeft = _useTooltip.tooltipLeft,
      tooltipTop = _useTooltip.tooltipTop,
      tooltipOpen = _useTooltip.tooltipOpen,
      showTooltip = _useTooltip.showTooltip,
      hideTooltip = _useTooltip.hideTooltip; // returns a number array with totals for each and every date


  var totals = graphData.reduce(function (ret, cur) {
    var t = keysToInclude.reduce(function (dailyTotal, k) {
      dailyTotal += +cur[k];
      return dailyTotal;
    }, 0);
    ret.push(t);
    return ret;
  }, []); // set maximum width and height for X-Axis and Y-Axis

  var xMax = width - 40;
  var yMax = height - 20; // getter function to get the category value for each
  // date - categoryAPI is obtained from props

  var getCategory = function getCategory(d) {
    return d[categoryAPI];
  }; // scales for X-Axis - each date


  var xScale = scaleBand({
    domain: graphData.map(getCategory),
    padding: 0.2
  }); // scales for Y-Axis - 0 to maximum of totals in each dates

  var yScale = scaleLinear({
    domain: [0, Math.max.apply(Math, _toConsumableArray(totals))],
    nice: true
  }); // scales for colorings for each key in bar chart - one to one mapping

  var color = scaleOrdinal({
    domain: keysToInclude,
    range: colorArray
  });
  xScale.rangeRound([0, xMax]);
  yScale.range([yMax, 0]);
  var myChartRef = /*#__PURE__*/React.createRef();

  var handleMouseOver = function handleMouseOver(event, value) {
    var position = myChartRef.current.getBoundingClientRect();
    var coords = localPoint(event.target.ownerSVGElement, event);
    showTooltip({
      tooltipLeft: coords.x,
      tooltipTop: coords.y - position.height - 60,
      tooltipData: value
    });
  };

  var tooltipStyles = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({
    zIndex: 100000,
    backgroundColor: colors.navyBlue[500],
    minWidth: "110px",
    borderRadius: "8px",
    display: "inline-block",
    whiteSpace: "pre-line"
  }, spacing["pl-3"]), spacing["pr-5"]), spacing["pt-3"]), spacing["pb-4"]), {}, {
    textAlign: "left"
  });

  var sumArray = function sumArray(arr) {
    return arr.reduce(function (a, b) {
      return a + b;
    }, 0);
  };

  var maxValue = Math.max.apply(Math, graphData.map(function (d) {
    return sumArray(Object.keys(d).splice(1).map(function (k) {
      return d[k];
    }));
  }));
  var yScaleGrid = scaleLinear({
    domain: [0, maxValue],
    nice: true
  });
  yScaleGrid.range([yMax, 0]);
  yScaleGrid.ticks(axisNum);
  var ticks = yScaleGrid.ticks(axisNum);
  var tickFormats = yScaleGrid.tickFormat(axisNum, "~s");
  ticks.map(tickFormats);
  return /*#__PURE__*/React.createElement("div", {
    className: classes.root
  }, /*#__PURE__*/React.createElement("svg", {
    width: width,
    height: height,
    ref: myChartRef,
    className: classes.chartContainer
  }, /*#__PURE__*/React.createElement(Group, {
    left: 22,
    top: 7,
    width: width,
    height: height
  }, /*#__PURE__*/React.createElement(AxisLeft, {
    scale: yScaleGrid,
    stroke: "transparent",
    tickStroke: "transparent",
    tickValues: ticks,
    tickFormat: tickFormats,
    left: -15,
    top: 3,
    tickLabelProps: function tickLabelProps() {
      return {
        fill: colors.neutral[300],
        fontSize: 12
      };
    }
  }), /*#__PURE__*/React.createElement(GridRows, {
    scale: yScaleGrid,
    width: xMax,
    numTicks: axisNum
  }), /*#__PURE__*/React.createElement(BarStack, {
    data: graphData,
    keys: keysToInclude,
    x: getCategory,
    xScale: xScale,
    yScale: yScale,
    color: color
  }, function (barStacks) {
    return barStacks.reverse().map(function (barStack) {
      return barStack.bars.map(function (bar) {
        return /*#__PURE__*/React.createElement("rect", {
          className: classes.bar,
          key: "bar-stack-".concat(barStack.index, "-").concat(bar.index),
          x: bar.x,
          y: bar.y,
          ry: 2,
          height: bar.height + 3 + bar.y > yMax ? bar.height : bar.height + 3,
          width: 6,
          fill: colors[bar.color][colorShade[barStack.index] || 500],
          onMouseOver: function onMouseOver(ev) {
            return handleMouseOver(ev, bar);
          },
          onMouseOut: hideTooltip
        }, /*#__PURE__*/React.createElement("animate", {
          attributeName: "height",
          from: 0,
          to: bar.height + 3 + bar.y > yMax ? bar.height : bar.height + 3,
          dur: "0.3",
          fill: "freeze"
        }), /*#__PURE__*/React.createElement("animate", {
          attributeName: "y",
          from: yMax,
          to: bar.y,
          dur: "0.3",
          fill: "freeze"
        }), /*#__PURE__*/React.createElement("animate", {
          attributeName: "opacity",
          from: 0,
          to: 1,
          dur: "0.3",
          fill: "freeze"
        }));
      });
    });
  }))), /*#__PURE__*/React.createElement("div", {
    className: classes.legend
  }, keysToInclude.map(function (key, index) {
    return /*#__PURE__*/React.createElement("div", {
      className: classes.legendOption,
      key: "legeng-".concat(index)
    }, legendVisualizer[index] && /*#__PURE__*/React.createElement("div", {
      className: classes.legendOptionIcon
    }, legendVisualizer[index]), !legendVisualizer[index] && /*#__PURE__*/React.createElement(Typography, {
      variant: "f2-12",
      weight: "bold",
      className: classes.legendOptionText
    }, key), /*#__PURE__*/React.createElement("svg", {
      width: 4,
      height: 20,
      className: classes.legendOptionColor
    }, /*#__PURE__*/React.createElement("rect", {
      ry: 2,
      height: 20,
      width: 4,
      fill: colors[colorArray[index]][colorShade[index] || 500]
    })));
  })), tooltipOpen && /*#__PURE__*/React.createElement(TooltipWithBounds // set this to random so it correctly updates with parent bounds
  , {
    key: Math.random(),
    top: tooltipTop,
    left: tooltipLeft,
    style: tooltipStyles
  }, /*#__PURE__*/React.createElement("div", {
    className: classes.tooltipContainer
  }, /*#__PURE__*/React.createElement(Typography, {
    variant: "f2-12",
    gutterBottom: true
  }, tooltipData.bar.data[categoryAPI]), keysToInclude.map(function (key, index) {
    return /*#__PURE__*/React.createElement("div", {
      className: classes.tooltipMetric
    }, legendVisualizer[index] && /*#__PURE__*/React.createElement("div", {
      className: classes.tooltipIcon
    }, legendVisualizer[index]), !legendVisualizer[index] && /*#__PURE__*/React.createElement(Typography, {
      variant: "f2-12",
      weight: "bold",
      className: classes.tooltipIcon
    }, key), /*#__PURE__*/React.createElement(Typography, {
      variant: "f1-12",
      weight: "bold",
      color: "white",
      className: classes.tooltipText
    }, tooltipData.bar.data[key], " ", type));
  }))));
};

BarGraphMultiple.propTypes = {
  height: PropTypes.number,
  width: PropTypes.number,
  type: PropTypes.string,
  graphData: PropTypes.instanceOf(Array).isRequired,
  colorArray: PropTypes.instanceOf(Array).isRequired,
  colorShade: PropTypes.instanceOf(Array),
  legendVisualizer: PropTypes.instanceOf(Array)
};
BarGraphMultiple.defaultProps = {
  height: 300,
  width: 300,
  type: "impressions"
};
export default BarGraphMultiple;