import { useKitDispatch } from '../KitStoreProvider/index.js';
import { convertDataStruct } from './metric.js';
import MetricActions from './MetricActions.js';
import MetricLegend from './MetricLegend.js';
import { MetricLegendTabStyle } from './styled.js';
import TooltipFormatter from './TooltipFormatter.js';
import { GraphType } from './type.js';
import useParrotTranslation from '../../hooks/useParrotTranslation.js';
import cs from 'classnames';
import dayjs from 'dayjs';
import React__default, { useState, useMemo, useCallback } from 'react';
import { ResponsiveContainer, AreaChart, XAxis, YAxis, Tooltip, Area } from 'recharts';
import { ChartActions } from '../../store/chart.js';

var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
const RenderChart = (props) => {
  const {
    metricName,
    showLegend,
    syncId,
    showXAxis,
    yAxisAlign,
    height,
    type,
    mode = "legend",
    dropdown,
    onLabelsChange,
    metric,
    yAxisProps,
    xAxisProps,
    actionsProps,
    tooltipProps
  } = props;
  const { t } = useParrotTranslation();
  const dispatch = useKitDispatch();
  const [deselected, setDeselected] = useState([]);
  const streams = useMemo(() => metric.sample_streams, [metric]);
  const legends = useMemo(() => {
    return metric.sample_streams.map((stream) => stream.legend);
  }, [metric.sample_streams]);
  const areaChartData = useMemo(
    () => convertDataStruct(streams.map((stream) => stream.points)),
    [streams]
  );
  const onLegendClick = useCallback(
    (id) => {
      setDeselected((prev) => {
        const include = prev.includes(id);
        const newDeselected = include ? prev.filter((r) => r !== id) : [...prev, id];
        onLabelsChange == null ? void 0 : onLabelsChange(newDeselected);
        return newDeselected.length >= streams.length ? prev : newDeselected;
      });
    },
    [onLabelsChange, streams]
  );
  const hidePointer = useCallback(() => {
    dispatch({
      type: ChartActions.SET_POINTER,
      payload: { visible: false, uuid: syncId }
    });
  }, [dispatch, syncId]);
  const handleMouseMove = useCallback(
    (e) => {
      var _a;
      if (e.isTooltipActive) {
        const { chartX, activePayload } = e;
        if (!((_a = activePayload == null ? void 0 : activePayload[0]) == null ? void 0 : _a.payload)) {
          return;
        }
        dispatch({
          type: ChartActions.SET_POINTER,
          payload: {
            uuid: syncId,
            visible: true,
            left: chartX,
            text: dayjs(Number(activePayload[0].payload.t)).format(
              "MM-DD HH:mm:ss"
            ),
            value: activePayload[0].payload.v
          }
        });
      }
    },
    [dispatch, syncId]
  );
  if (!(streams == null ? void 0 : streams.length) || streams.every((stream) => {
    var _a;
    return !((_a = stream.points) == null ? void 0 : _a.length);
  })) {
    return /* @__PURE__ */ React__default.createElement("div", { className: MetricLegendTabStyle }, /* @__PURE__ */ React__default.createElement("div", { className: "name-toolbar" }, /* @__PURE__ */ React__default.createElement(
      MetricLegend,
      {
        streams,
        metricName,
        deselected,
        onClick: onLegendClick,
        legends
      }
    )), /* @__PURE__ */ React__default.createElement("div", { className: cs("content", mode === "single" && "single-content") }, t("metric.empty")));
  }
  return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("div", { className: "metric-toolbar" }, showLegend && /* @__PURE__ */ React__default.createElement(
    MetricLegend,
    {
      streams,
      metricName,
      deselected,
      onClick: onLegendClick,
      legends
    }
  ), (actionsProps == null ? void 0 : actionsProps.show) && /* @__PURE__ */ React__default.createElement(MetricActions, __spreadValues({ dropdown }, actionsProps))), /* @__PURE__ */ React__default.createElement(ResponsiveContainer, { height }, /* @__PURE__ */ React__default.createElement(
    AreaChart,
    {
      style: { backgroundColor: "white" },
      margin: showLegend ? { top: 10, left: 10, right: 10, bottom: 0 } : { top: 20, left: 10, right: 10, bottom: 5 },
      data: areaChartData,
      syncId,
      onMouseLeave: hidePointer,
      onMouseMove: handleMouseMove
    },
    /* @__PURE__ */ React__default.createElement(
      XAxis,
      __spreadValues({
        hide: !showXAxis,
        dataKey: "t",
        axisLine: false,
        tickLine: false,
        type: "number"
      }, xAxisProps)
    ),
    /* @__PURE__ */ React__default.createElement(
      YAxis,
      __spreadValues({
        width: 200,
        mirror: true,
        allowDataOverflow: true,
        axisLine: false,
        tickLine: false,
        orientation: yAxisAlign
      }, yAxisProps)
    ),
    /* @__PURE__ */ React__default.createElement(
      Tooltip,
      __spreadValues({
        content: tooltipProps.format && /* @__PURE__ */ React__default.createElement(
          TooltipFormatter,
          {
            deselected,
            legends,
            format: tooltipProps.format
          }
        )
      }, tooltipProps)
    ),
    streams.map((item, index) => {
      if (deselected.includes(item.legend.id)) {
        return null;
      }
      return /* @__PURE__ */ React__default.createElement(
        Area,
        {
          key: index,
          dataKey: `v${index}`,
          stackId: type === GraphType.Stack ? "stack" : void 0,
          stroke: item.legend.stroke ? `${item.legend.color}1A` : item.legend.color,
          fill: item.legend.fill,
          isAnimationActive: false,
          activeDot: {
            stroke: item.legend.color,
            r: 4,
            strokeWidth: 2,
            fill: "white"
          }
        }
      );
    })
  )));
};
var RenderChart$1 = RenderChart;

export { RenderChart$1 as default };
