import { CalendarClockDateTime16SecondaryIcon, CalendarClockDateTime16GradientBlueIcon, CalendarTimeRecord16Icon } from '@cloudtower/icons-react';
import { cx } from '@linaria/core';
import Icon from '../../core/Icon/index.js';
import Input from '../../core/Input/index.js';
import Tooltip from '../../core/Tooltip/index.js';
import { Typo } from '../../core/Typo/index.js';
import AbsoluteDate from './AbsoluteDate.js';
import { DateRangePickerStyle, ResetPopoverStyle } from './DateRangePicker.style.js';
import RelativeTime from './RelativeTime.js';
import TabMenu from '../TabMenu/index.js';
import useParrotTranslation from '../../hooks/useParrotTranslation.js';
import { Popover } from 'antd';
import dayjs from 'dayjs';
import React__default, { useState, useEffect, useRef } from 'react';
import { getDateText } from './common.js';

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 = useRef(null);
  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.createElement("div", { className: "relative-time-container" }, /* @__PURE__ */ React__default.createElement(
      RelativeTime,
      {
        value: relativeTime,
        onChange: (time) => onRelativeTimeChange == null ? void 0 : onRelativeTimeChange(time),
        config: relativeTimeSelectOptions
      }
    ));
  } else if (mode === "absolute") {
    return /* @__PURE__ */ React__default.createElement("div", { className: "absolute-time-container" }, /* @__PURE__ */ React__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.createElement("div", { className: "relative-time-container" }, /* @__PURE__ */ React__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.createElement("div", { className: "absolute-time-container" }, /* @__PURE__ */ React__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.createElement(
      TabMenu,
      {
        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.createElement(React__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(item.value[0]).format("YYYY-MM-DD hh:mm:ss")} - ${dayjs(
        item.value[1]
      ).format("YYYY-MM-DD hh:mm:ss")}` : getDateText(item.value, t);
      const obj = Array.isArray(item.value) ? [dayjs(item.value[0]), dayjs(item.value[1])] : item.value;
      return /* @__PURE__ */ React__default.createElement(
        "li",
        {
          key: index,
          className: Typo.Label.l2_regular,
          onClick: () => onSelect(obj)
        },
        text
      );
    });
  }
  return /* @__PURE__ */ React__default.createElement(DateRangePickerStyle.History, null, /* @__PURE__ */ React__default.createElement("header", { className: Typo.Heading.h2_regular_title }, t("components.date_range_picker_history_title")), /* @__PURE__ */ React__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] = useState(false);
  const [type, setType] = useState("relative");
  const [range, setRange] = 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();
      const pastDay = dayjs().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);
  }
  useEffect(() => {
    if (isRelativeValue) {
      const today = dayjs();
      const pastDay = dayjs().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.createElement(React__default.Fragment, null, getDateText(value, t));
    } else if (isAbsoluteValue) {
      return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(
        Input,
        {
          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.createElement("span", { className: "concat-symbol-block" }, "-"), /* @__PURE__ */ React__default.createElement(
        Input,
        {
          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(minDate);
        _value[0] = start.isBefore(_minDate) ? _minDate : start;
      }
      if (maxDate && end) {
        const _maxDate = dayjs(maxDate);
        _value[1] = end.isAfter(_maxDate) ? _maxDate : end;
      }
      handleChange(type2, _value);
    }
    handleChange(type2, value2);
  }
  return /* @__PURE__ */ React__default.createElement(
    DateRangePickerStyle.Wrapper,
    {
      className: cx(
        "date-range-picker",
        datePickerVisible && "active",
        size === "large" && "large",
        size === "medium" && "medium"
      )
    },
    /* @__PURE__ */ React__default.createElement(
      Icon,
      {
        className: "default-calendar-icon",
        iconWidth: 16,
        iconHeight: 16,
        src: CalendarClockDateTime16SecondaryIcon
      }
    ),
    /* @__PURE__ */ React__default.createElement(
      Icon,
      {
        className: "hover-calendar-icon",
        iconWidth: 16,
        iconHeight: 16,
        src: CalendarClockDateTime16GradientBlueIcon
      }
    ),
    /* @__PURE__ */ React__default.createElement(
      Popover,
      {
        overlayClassName: cx(DateRangePickerStyle.Popover, ResetPopoverStyle),
        visible: datePickerVisible,
        content: /* @__PURE__ */ React__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.createElement("div", { className: "date-input-content" }, displayRangeRender())
    ),
    history ? /* @__PURE__ */ React__default.createElement(
      Popover,
      {
        placement: "bottomRight",
        trigger: ["click"],
        content: /* @__PURE__ */ React__default.createElement(
          TimePickerHistory,
          {
            history: (_a = history.dateRangeHistories[history.scope]) != null ? _a : [],
            onSelect: handleSelectHistory
          }
        ),
        overlayClassName: ResetPopoverStyle
      },
      /* @__PURE__ */ React__default.createElement(
        Tooltip,
        {
          trigger: "hover",
          overlay: t("components.date_range_picker_history_title")
        },
        /* @__PURE__ */ React__default.createElement(Icon, { className: "past-time-icon", src: CalendarTimeRecord16Icon })
      )
    ) : null
  );
};
var DateRangePicker$1 = DateRangePicker;

export { AbsoluteDate, RelativeTime, DateRangePicker$1 as default };
