'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var iconsReact = require('@cloudtower/icons-react');
var core = require('@linaria/core');
var index = require('../../core/Icon/index.js');
var index$4 = require('../../core/Input/index.js');
var index$1 = require('../../core/Tooltip/index.js');
var index$3 = require('../../core/Typo/index.js');
var AbsoluteDate = require('./AbsoluteDate.js');
var DateRangePicker_style = require('./DateRangePicker.style.js');
var RelativeTime = require('./RelativeTime.js');
var index$2 = require('../TabMenu/index.js');
var useParrotTranslation = require('../../hooks/useParrotTranslation.js');
var antd = require('antd');
var dayjs = require('dayjs');
var React = require('react');
var common = require('./common.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var dayjs__default = /*#__PURE__*/_interopDefault(dayjs);
var React__default = /*#__PURE__*/_interopDefault(React);

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
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;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const TimeRange = (props) => {
  const {
    visible,
    type,
    relativeTime,
    range,
    mode = ["relative", "absolute"],
    minDate,
    maxDate,
    maxRange,
    onTypeChange,
    onRelativeTimeChange,
    onAbsoluteTimeOk,
    onAbsoluteTimeChange,
    relativeTimeSelectOptions
  } = props;
  const { t } = useParrotTranslation();
  const absoluteDateRef = React.useRef(null);
  React.useEffect(() => {
    var _a, _b;
    if (!visible) {
      (_b = (_a = absoluteDateRef.current) == null ? void 0 : _a.reset) == null ? void 0 : _b.call(_a);
    }
  }, [visible]);
  if (mode === "relative") {
    return /* @__PURE__ */ React__default.default.createElement("div", { className: "relative-time-container" }, /* @__PURE__ */ React__default.default.createElement(
      RelativeTime,
      {
        value: relativeTime,
        onChange: (time) => onRelativeTimeChange == null ? void 0 : onRelativeTimeChange(time),
        config: relativeTimeSelectOptions
      }
    ));
  } else if (mode === "absolute") {
    return /* @__PURE__ */ React__default.default.createElement("div", { className: "absolute-time-container" }, /* @__PURE__ */ React__default.default.createElement(
      AbsoluteDate,
      {
        ref: absoluteDateRef,
        range: range || [null, null],
        minDate,
        maxDate,
        onChange: (range2) => onAbsoluteTimeChange == null ? void 0 : onAbsoluteTimeChange(range2),
        onOk: (range2) => onAbsoluteTimeOk == null ? void 0 : onAbsoluteTimeOk(range2)
      }
    ));
  } else {
    const tabs = [
      {
        key: "relative",
        title: t("components.relative_time"),
        children: /* @__PURE__ */ React__default.default.createElement("div", { className: "relative-time-container" }, /* @__PURE__ */ React__default.default.createElement(
          RelativeTime,
          {
            value: relativeTime,
            onChange: (time) => onRelativeTimeChange == null ? void 0 : onRelativeTimeChange(time),
            config: relativeTimeSelectOptions
          }
        ))
      },
      {
        key: "absolute",
        title: t("components.absolute_time"),
        children: /* @__PURE__ */ React__default.default.createElement("div", { className: "absolute-time-container" }, /* @__PURE__ */ React__default.default.createElement(
          AbsoluteDate,
          {
            ref: absoluteDateRef,
            range: range || [null, null],
            minDate,
            maxDate,
            maxRange,
            onChange: (range2) => onAbsoluteTimeChange == null ? void 0 : onAbsoluteTimeChange(range2),
            onOk: (range2) => onAbsoluteTimeOk == null ? void 0 : onAbsoluteTimeOk(range2)
          }
        ))
      }
    ].filter((item) => mode.includes(item.key));
    return /* @__PURE__ */ React__default.default.createElement(
      index$2,
      {
        selectedKey: type,
        tabs,
        onChange: onTypeChange,
        size: "small"
      }
    );
  }
};
const TimePickerHistory = (props) => {
  const { history, onSelect } = props;
  const { t } = useParrotTranslation();
  function contentRender() {
    if (!history.length) {
      return /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null, t("components.empty_search_history"));
    }
    return history.sort((a, b) => b.timestamp - a.timestamp).map((item, index) => {
      const text = Array.isArray(item.value) ? `${dayjs__default.default(item.value[0]).format("YYYY-MM-DD hh:mm:ss")} - ${dayjs__default.default(
        item.value[1]
      ).format("YYYY-MM-DD hh:mm:ss")}` : common.getDateText(item.value, t);
      const obj = Array.isArray(item.value) ? [dayjs__default.default(item.value[0]), dayjs__default.default(item.value[1])] : item.value;
      return /* @__PURE__ */ React__default.default.createElement(
        "li",
        {
          key: index,
          className: index$3.Typo.Label.l2_regular,
          onClick: () => onSelect(obj)
        },
        text
      );
    });
  }
  return /* @__PURE__ */ React__default.default.createElement(DateRangePicker_style.DateRangePickerStyle.History, null, /* @__PURE__ */ React__default.default.createElement("header", { className: index$3.Typo.Heading.h2_regular_title }, t("components.date_range_picker_history_title")), /* @__PURE__ */ React__default.default.createElement("ul", null, contentRender()));
};
const DateRangePicker = (props) => {
  var _a;
  const {
    size = "medium",
    value,
    history,
    mode = ["relative", "absolute"],
    minDate,
    maxDate,
    maxRange,
    onChange,
    relativeTimeSelectOptions
  } = props;
  const { t } = useParrotTranslation();
  const [datePickerVisible, setDatePickerVisible] = React.useState(false);
  const [type, setType] = React.useState("relative");
  const [range, setRange] = React.useState(
    Array.isArray(value) ? value : void 0
  );
  const relativeTime = !Array.isArray(value) ? value : void 0;
  const isRelativeValue = value && !Array.isArray(value);
  const isAbsoluteValue = value && Array.isArray(value);
  function handleChange(type2, time) {
    var _a2, _b;
    const rangeHistory = [
      ...(_a2 = history == null ? void 0 : history.dateRangeHistories[history.scope]) != null ? _a2 : []
    ];
    if (type2 === "absolute" && Array.isArray(time)) {
      const value2 = time.map((item) => (item == null ? void 0 : item.format()) || "");
      rangeHistory.push({
        type: type2,
        value: value2,
        timestamp: Date.now()
      });
      onChange == null ? void 0 : onChange(type2, time, time);
    } else if (type2 === "relative" && !Array.isArray(time)) {
      rangeHistory.push({
        type: type2,
        value: time,
        timestamp: Date.now()
      });
      const today = dayjs__default.default();
      const pastDay = dayjs__default.default().subtract(time.value, time.unit);
      onChange == null ? void 0 : onChange(type2, time, [today, pastDay]);
    }
    history == null ? void 0 : history.setDateRangeHistory(__spreadProps(__spreadValues({}, (_b = history == null ? void 0 : history.dateRangeHistories) != null ? _b : {}), {
      [history.scope]: rangeHistory
    }));
    setDatePickerVisible(false);
  }
  React.useEffect(() => {
    if (isRelativeValue) {
      const today = dayjs__default.default();
      const pastDay = dayjs__default.default().subtract(value.value, value.unit);
      setType("relative");
      onChange == null ? void 0 : onChange("relative", value, [today, pastDay]);
    } else if (isAbsoluteValue) {
      setRange(value);
      setType("absolute");
      onChange == null ? void 0 : onChange("absolute", value, value);
    }
  }, [value]);
  function displayRangeRender() {
    var _a2, _b;
    if (isRelativeValue) {
      return /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null, common.getDateText(value, t));
    } else if (isAbsoluteValue) {
      return /* @__PURE__ */ React__default.default.createElement(React__default.default.Fragment, null, /* @__PURE__ */ React__default.default.createElement(
        index$4,
        {
          readOnly: true,
          value: (_a2 = value[0]) == null ? void 0 : _a2.format("YYYY-MM-DD HH:mm:ss"),
          placeholder: "YYYY-MM-DD HH:mm:ss"
        }
      ), /* @__PURE__ */ React__default.default.createElement("span", { className: "concat-symbol-block" }, "-"), /* @__PURE__ */ React__default.default.createElement(
        index$4,
        {
          readOnly: true,
          value: (_b = value[1]) == null ? void 0 : _b.format("YYYY-MM-DD HH:mm:ss"),
          placeholder: "YYYY-MM-DD HH:mm:ss"
        }
      ));
    }
  }
  function handleSelectHistory(value2) {
    const type2 = Array.isArray(value2) ? "absolute" : "relative";
    if (type2 === "absolute" && Array.isArray(value2)) {
      const _value = [...value2];
      const [start, end] = _value;
      if (minDate && start) {
        const _minDate = dayjs__default.default(minDate);
        _value[0] = start.isBefore(_minDate) ? _minDate : start;
      }
      if (maxDate && end) {
        const _maxDate = dayjs__default.default(maxDate);
        _value[1] = end.isAfter(_maxDate) ? _maxDate : end;
      }
      handleChange(type2, _value);
    }
    handleChange(type2, value2);
  }
  return /* @__PURE__ */ React__default.default.createElement(
    DateRangePicker_style.DateRangePickerStyle.Wrapper,
    {
      className: core.cx(
        "date-range-picker",
        datePickerVisible && "active",
        size === "large" && "large",
        size === "medium" && "medium"
      )
    },
    /* @__PURE__ */ React__default.default.createElement(
      index,
      {
        className: "default-calendar-icon",
        iconWidth: 16,
        iconHeight: 16,
        src: iconsReact.CalendarClockDateTime16SecondaryIcon
      }
    ),
    /* @__PURE__ */ React__default.default.createElement(
      index,
      {
        className: "hover-calendar-icon",
        iconWidth: 16,
        iconHeight: 16,
        src: iconsReact.CalendarClockDateTime16GradientBlueIcon
      }
    ),
    /* @__PURE__ */ React__default.default.createElement(
      antd.Popover,
      {
        overlayClassName: core.cx(DateRangePicker_style.DateRangePickerStyle.Popover, DateRangePicker_style.ResetPopoverStyle),
        visible: datePickerVisible,
        content: /* @__PURE__ */ React__default.default.createElement(
          TimeRange,
          {
            visible: datePickerVisible,
            type,
            range,
            relativeTime,
            mode,
            minDate,
            maxDate,
            maxRange,
            onTypeChange: setType,
            onRelativeTimeChange: (time) => {
              handleChange("relative", time);
            },
            onAbsoluteTimeChange: setRange,
            onAbsoluteTimeOk: (range2) => {
              handleChange("absolute", range2);
            },
            relativeTimeSelectOptions
          }
        ),
        placement: "bottomLeft",
        trigger: ["click"],
        onVisibleChange: (visible) => {
          if (!visible && (Array.isArray(value) || !value)) {
            setRange(value);
          }
          setDatePickerVisible(visible);
        }
      },
      /* @__PURE__ */ React__default.default.createElement("div", { className: "date-input-content" }, displayRangeRender())
    ),
    history ? /* @__PURE__ */ React__default.default.createElement(
      antd.Popover,
      {
        placement: "bottomRight",
        trigger: ["click"],
        content: /* @__PURE__ */ React__default.default.createElement(
          TimePickerHistory,
          {
            history: (_a = history.dateRangeHistories[history.scope]) != null ? _a : [],
            onSelect: handleSelectHistory
          }
        ),
        overlayClassName: DateRangePicker_style.ResetPopoverStyle
      },
      /* @__PURE__ */ React__default.default.createElement(
        index$1,
        {
          trigger: "hover",
          overlay: t("components.date_range_picker_history_title")
        },
        /* @__PURE__ */ React__default.default.createElement(index, { className: "past-time-icon", src: iconsReact.CalendarTimeRecord16Icon })
      )
    ) : null
  );
};
var DateRangePicker$1 = DateRangePicker;

exports.AbsoluteDate = AbsoluteDate;
exports.RelativeTime = RelativeTime;
exports.default = DateRangePicker$1;
