import { useKitDispatch } from '../KitStoreProvider/index.js';
import LineChartLegend from './LineChartLegend.js';
import { MetricLegendTabStyle } from './styled.js';
import TooltipFormatter from './TooltipFormatter.js';
import { ILineChartGraphType } from './type.js';
import { convertLineChartDataStruct, getYAxisDomain, getLineChartXAxisDomain, lineChartXaxisCal, lineChartYaxisTickFormatter, lineChartTickFormatter } from './utils.js';
import useParrotTranslation from '../../hooks/useParrotTranslation.js';
import { Empty } from 'antd';
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 LineChartToolBar from './LineChartToolBar.js';
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",
    dropdownProps,
    onLabelsChange,
    metric,
    yAxisProps,
    xAxisProps,
    actionsProps,
    tooltipProps,
    width,
    dateRange = [dayjs(), dayjs()],
    emptyText,
    emptyIcon
  } = props;
  const { t } = useParrotTranslation();
  const dispatch = useKitDispatch();
  const [deselected, setDeselected] = useState([]);
  const [hovering, setHovering] = useState([]);
  const [hoveringSelf, setHoveringSelf] = useState([]);
  const [tempDeselected, setTempDeselected] = 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(
    () => convertLineChartDataStruct(streams.map((stream) => stream.points)),
    [streams]
  );
  const yDomain = getYAxisDomain(areaChartData, type, metric.unit);
  const xDomain = getLineChartXAxisDomain(dateRange, dateRange[1].valueOf());
  const xTicks = lineChartXaxisCal(xDomain[1], dateRange, width);
  const onLegendClick = useCallback(
    (id) => {
      setDeselected((prev) => {
        var _a;
        const currentDeselected = tempDeselected.length ? tempDeselected : prev;
        if (currentDeselected.length === 0) {
          return streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id);
        }
        if (currentDeselected.length === streams.length - 1) {
          const highlightedId = (_a = streams.find(
            (stream) => !currentDeselected.includes(stream.legend.id)
          )) == null ? void 0 : _a.legend.id;
          if (id === highlightedId) {
            return [];
          } else {
            return currentDeselected.filter(
              (deselectedId) => deselectedId !== id
            );
          }
        }
        const isHighlighted = !currentDeselected.includes(id);
        if (isHighlighted) {
          return [...currentDeselected, id];
        } else {
          return currentDeselected.filter(
            (deselectedId) => deselectedId !== id
          );
        }
      });
      if (tempDeselected.length) {
        setTempDeselected([]);
      }
    },
    [streams, tempDeselected]
  );
  const onLegendHover = useCallback(
    (method, id) => {
      if (method === "enter") {
        if (deselected.length) {
          setTempDeselected(deselected);
          if (deselected.includes(id)) {
            setDeselected(
              streams.map((stream) => stream.legend.id).filter(
                (legendId) => legendId !== id && deselected.includes(legendId)
              )
            );
            setHovering(
              streams.map((stream) => stream.legend.id).filter((legendId) => legendId === id)
            );
            setHoveringSelf(
              streams.map((stream) => stream.legend.id).filter((legendId) => legendId === id)
            );
          } else {
            if (deselected.length === streams.length - 1) {
              setDeselected([]);
              setHovering(
                streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
              );
            } else {
              setHovering(
                streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
              );
              setHoveringSelf(
                streams.map((stream) => stream.legend.id).filter(
                  (legendId) => legendId !== id && !deselected.includes(legendId)
                )
              );
            }
          }
        } else {
          setHovering(
            streams.map((stream) => stream.legend.id).filter((legendId) => legendId !== id)
          );
        }
      } else {
        if (tempDeselected.length) {
          setDeselected(tempDeselected);
          setTempDeselected([]);
        }
        setHovering([]);
        setHoveringSelf([]);
      }
    },
    [deselected, streams, tempDeselected]
  );
  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(
      LineChartLegend,
      {
        streams,
        metricName,
        deselected,
        hovering,
        hovereringSelf: hoveringSelf,
        onClick: onLegendClick,
        onHover: onLegendHover,
        legends
      }
    )), /* @__PURE__ */ React__default.createElement("div", { className: cs("content", mode === "single" && "single-content") }, /* @__PURE__ */ React__default.createElement(
      Empty,
      {
        description: emptyText || t("metric.empty"),
        image: emptyIcon ? emptyIcon : null,
        imageStyle: emptyIcon ? {} : { display: "none" }
      }
    )));
  }
  return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(
    LineChartToolBar,
    {
      showLegend,
      streams,
      metricName,
      deselected,
      hovering,
      hoveringSelf,
      onLegendClick,
      legends,
      actionsProps,
      dropdownProps,
      onLegendHover
    }
  ), /* @__PURE__ */ React__default.createElement(ResponsiveContainer, { height }, /* @__PURE__ */ React__default.createElement(
    AreaChart,
    {
      style: { backgroundColor: "white" },
      margin: showLegend ? { top: 10, left: -20, right: 0, bottom: 0 } : { top: 20, left: -20, right: 0, 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",
        ticks: xTicks,
        domain: xDomain,
        tickFormatter: (tick) => lineChartTickFormatter(tick, dateRange)
      }, xAxisProps)
    ),
    /* @__PURE__ */ React__default.createElement(
      YAxis,
      __spreadValues({
        width: 200,
        mirror: true,
        axisLine: false,
        tickLine: false,
        allowDecimals: false,
        domain: yDomain,
        orientation: yAxisAlign,
        tick: {
          dx: 20,
          dy: 16,
          fontSize: 12
        },
        ticks: [yDomain[1] / 2, yDomain[1]],
        tickFormatter: (tick) => lineChartYaxisTickFormatter(tick, metric.unit)
      }, yAxisProps)
    ),
    /* @__PURE__ */ React__default.createElement(
      Tooltip,
      __spreadValues({
        wrapperStyle: { left: 20 },
        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 === ILineChartGraphType.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"
          },
          opacity: hovering.includes(item.legend.id) ? 0.3 : 1
        }
      );
    })
  )));
};
var RenderChart$1 = RenderChart;

export { RenderChart$1 as default };
