import { Component as W } from "react";
import t from "prop-types";
import b from "react-dom";
import j from "react-onclickoutside";
import o from "moment";
import p from "../../utils/classNames.js";
import { isNil as R, isNull as T, isEqual as _ } from "es-toolkit/predicate";
import y from "./DatePicker.js";
import $ from "../../utils/getDropDirection.js";
const S = ({ text: C }) => /* @__PURE__ */ React.createElement("span", { className: "placeholder" }, C), q = {
  startValue: t.object,
  endValue: t.object,
  defaultStartValue: t.object,
  defaultEndValue: t.object,
  minValue: t.object,
  maxValue: t.object,
  onRangeChange: t.func,
  locale: t.string,
  textDefault: t.oneOfType([t.string, t.node]),
  textToday: t.oneOfType([t.string, t.node]),
  textLastWeek: t.oneOfType([t.string, t.node]),
  textLastMonth: t.oneOfType([t.string, t.node]),
  textLastYear: t.oneOfType([t.string, t.node]),
  textCustom: t.oneOfType([t.string, t.node]),
  textApply: t.oneOfType([t.string, t.node]),
  textCancel: t.oneOfType([t.string, t.node]),
  textFrom: t.oneOfType([t.string, t.node]),
  textTo: t.oneOfType([t.string, t.node]),
  className: t.string,
  dropdownClass: t.string,
  dropdownMenuClass: t.string,
  hasTimePicker: t.bool,
  customRangeOnly: t.bool,
  customPresets: t.arrayOf(
    t.shape({
      startValue: t.object.isRequired,
      endValue: t.object.isRequired,
      text: t.string.isRequired,
      onSelect: t.func
    })
  ),
  dropup: t.bool,
  pullRight: t.bool,
  autoDropDirection: t.bool,
  clearable: t.bool,
  onClear: t.func
}, w = {
  defaultStartValue: o().startOf("day"),
  defaultEndValue: o().endOf("day"),
  minValue: null,
  maxValue: null,
  locale: "en-GB",
  textDefault: "Select date range ...",
  textToday: "Today",
  textLastWeek: "Last week",
  textLastMonth: "Last month",
  textCustom: "Custom",
  textFrom: "From",
  textTo: "To",
  textApply: "Apply",
  textCancel: "Cancel",
  dropdownClass: "",
  dropdownMenuClass: "",
  hasTimePicker: !1,
  customRangeOnly: !1,
  customPresets: [
    {
      text: "Today",
      startValue: o().startOf("day"),
      endValue: o().endOf("day")
    },
    {
      text: "Last week",
      startValue: o().subtract(1, "weeks").startOf("isoWeek"),
      endValue: o().subtract(1, "weeks").endOf("isoWeek")
    },
    {
      text: "Last Month",
      startValue: o().subtract(1, "months").startOf("month"),
      endValue: o().subtract(1, "months").endOf("month")
    }
  ],
  onRangeChange: () => {
  },
  autoDropDirection: !0,
  dropup: !1,
  pullRight: !1,
  clearable: !1,
  onClear: () => {
  }
}, G = "dd L LT", H = "dd L", U = 600;
class E extends W {
  constructor(e) {
    super(e);
    const a = e.startValue ? e.startValue : e.defaultStartValue, s = e.endValue ? e.endValue : e.defaultEndValue;
    this.state = {
      internalStartValue: e.startValue,
      internalEndValue: e.endValue,
      isMounted: !1,
      isCustomVisible: e.customRangeOnly,
      isDropdownOpen: !1,
      customRangeStartValue: o(a),
      // default value for individual datepickers
      customRangeEndValue: o(s),
      // default value for individual datepickers
      isStartValid: !0,
      isEndValid: !0,
      dropdownToggleText: /* @__PURE__ */ React.createElement(S, { text: e.textDefault }),
      dropup: e.dropup,
      pullRight: e.pullRight
    }, this.toggleDropdownOpen = this.toggleDropdownOpen.bind(this), this.handleCustomToggle = this.handleCustomToggle.bind(this), this.handleCustomApply = this.handleCustomApply.bind(this), this.onStartChange = this.onStartChange.bind(this), this.getValidStartDates = this.getValidStartDates.bind(this), this.onEndChange = this.onEndChange.bind(this), this.getValidEndDates = this.getValidEndDates.bind(this), this.handleResetInternalState = this.handleResetInternalState.bind(this);
  }
  componentDidMount() {
    const { startValue: e, endValue: a, locale: s } = this.props;
    this.state.isMounted || this.setState({
      isMounted: !0
    }), e && a && this.update(e, a, s);
  }
  /**
   * Responsible for handling start/end values given from outside (controlled component context).
   * @param {object} nextProps - The next props.
   * @returns {undefined}
   */
  UNSAFE_componentWillReceiveProps(e) {
    const { startValue: a, endValue: s, textDefault: i, customRangeOnly: n, locale: l, defaultStartValue: d, defaultEndValue: r } = e, { internalStartValue: u, internalEndValue: c } = this.state, m = R(a) && R(s) && R(u) && R(c), g = T(a) && T(s);
    m || g ? this.setState({
      internalStartValue: void 0,
      internalEndValue: void 0,
      customRangeStartValue: d,
      customRangeEndValue: r,
      dropdownToggleText: /* @__PURE__ */ React.createElement(S, { text: i }),
      isCustomVisible: n,
      isDropdownOpen: !1,
      isStartValid: !0,
      isEndValid: !0,
      pullRight: e.pullRight,
      dropup: e.dropup
    }) : a !== this.props.startValue || s !== this.props.endValue ? this.update(a, s, l) : this.update(u, c, l);
  }
  /**
   * Converts start/end values to moments, makes them readable,
   * crafts a dropdownToggleText and updates state.
   * @param {object} startValue - the start date (date or moment).
   * @param {object} endValue - the start date (date or moment).
   * @param {object} locale - the locale to use.
   * @param {object} extras - additional state, which needs to update.
   * @param {object} callback - callback to be called, after state has changed.
   * @returns {undefined}
   */
  update(e, a, s, i, n) {
    const { hasTimePicker: l } = this.props, d = l ? G : H, r = l ? o(e) : o(e).startOf("day"), u = l ? o(a) : o(a).endOf("day"), c = `${r.locale(s).format(d)}`, m = `${u.locale(s).format(d)}`, g = c === m ? c : `${c} → ${m}`;
    this.setState(
      {
        internalStartValue: r,
        internalEndValue: u,
        customRangeStartValue: r,
        customRangeEndValue: u,
        dropdownToggleText: g,
        startValueText: c,
        endValueText: m,
        isStartValid: !0,
        isEndValid: !u.isBefore(r),
        ...i
      },
      () => {
        n && n(r, u);
      }
    );
  }
  handleResetInternalState(e) {
    e && (e.preventDefault(), e.stopPropagation());
    const { textDefault: a, customRangeOnly: s, defaultStartValue: i, defaultEndValue: n, pullRight: l, dropup: d, onClear: r } = this.props;
    this.setState({
      internalStartValue: void 0,
      internalEndValue: void 0,
      customRangeStartValue: i,
      customRangeEndValue: n,
      dropdownToggleText: /* @__PURE__ */ React.createElement(S, { text: a }),
      isCustomVisible: s,
      isDropdownOpen: !1,
      isStartValid: !0,
      isEndValid: !0,
      startValueText: null,
      endValueText: null,
      pullRight: l,
      dropup: d
    }), r();
  }
  /**
   * Gets called by wrapper component "onClickOutside".
   * Responsible for closing the dropdown when a click occured outside.
   * @returns {undefined}
   */
  handleClickOutside() {
    this.state.isMounted && this.setState({
      isDropdownOpen: !1
    });
  }
  /**
   * Toggles dropdown open status and visibility of custom range area.
   * @param {object} event - mouse event on toggle dropdown
   * @returns {undefined}
   */
  toggleDropdownOpen(e) {
    const a = b.findDOMNode(this.refDropdownToggle), s = b.findDOMNode(this.refDropdownMenu), i = this.isAutoDropActive() && !this.state.isDropdownOpen ? $(a, s) : {}, n = e.currentTarget.getBoundingClientRect().left;
    this.setState((l) => ({
      isDropdownOpen: !l.isDropdownOpen,
      isCustomVisible: this.props.customRangeOnly,
      ...i,
      pullRight: n + U > document.body.clientWidth
    }));
  }
  isAutoDropActive() {
    return !(!this.props.autoDropDirection || this.props.dropup || this.props.pullRight);
  }
  /**
   * Only gets called on manual change of datePicker (user interaction).
   * Has influence the validity of the end date.
   *
   * Important to note that the start date is not limited,
   * whereas the end date is limited by the start date (see 'getValidEndDates').
   *
   * @param {object} startValue - the start date (date or moment).
   * @param {object} isValidDate - if the date is valid or not.
   * @returns {undefined}
   */
  onStartChange(e, a) {
    const s = { isStartValid: !1 }, { hasTimePicker: i, minValue: n, maxValue: l } = this.props, { customRangeEndValue: d } = this.state;
    if (o.isMoment(e)) {
      const r = i ? e : o(e).startOf("day"), u = n ? r.isSameOrAfter(o(n)) : !0, c = l ? r.isSameOrBefore(o(l)) : !0, m = a && u && c;
      s.isStartValid = m, a && (s.customRangeStartValue = r, s.isEndValid = !d.isBefore(r));
    }
    this.setState(s);
  }
  /**
   * Only gets called on manual change of datePicker (user interaction)
   * @param {object} endValue - the start date (date or moment).
   * @param {object} isValidDate - if the date is valid or not.
   * @returns {undefined}
   */
  onEndChange(e, a) {
    const s = { isEndValid: !1 }, { hasTimePicker: i, minValue: n, maxValue: l } = this.props, { customRangeStartValue: d } = this.state;
    if (o.isMoment(e)) {
      const r = a ? e.endOf("minute") : e, u = i ? r : o(e).endOf("day"), c = n ? u.isSameOrAfter(o(n)) : !0, m = l ? u.isSameOrBefore(o(l)) : !0, g = a && c && m && u.isAfter(d);
      s.isEndValid = g, a && (s.customRangeEndValue = u);
    }
    this.setState(s);
  }
  /**
   * Callback method for DatePicker to limit selection in DatePicker.
   * @param {object} current - Current date in the loop.
   * @returns {undefined}
   */
  getValidStartDates(e) {
    const { minValue: a, maxValue: s } = this.props, i = o(this.state.customRangeEndValue);
    if (e.isSame(i, "day"))
      return !0;
    const n = a ? e.isSameOrAfter(o(a)) : !0, l = s ? e.isSameOrBefore(o(s)) : !0;
    return n && l;
  }
  /**
   * Callback method for DatePicker to limit selection in DatePicker.
   * End date has to be after start date.
   * @param {object} current - Current date in the loop.
   * @returns {undefined}
   */
  getValidEndDates(e) {
    const { minValue: a, maxValue: s } = this.props, i = o(this.state.customRangeStartValue);
    if (e.isSame(i, "day"))
      return !0;
    const n = a ? e.isSameOrAfter(o(a)) : !0, l = s ? e.isSameOrBefore(o(s)) : !0, d = e.isAfter(i);
    return n && l && d;
  }
  /**
   * Gets called when "custom ..." has been selected.
   * @returns {undefined}
   */
  handleCustomToggle() {
    this.setState((e) => ({
      isCustomVisible: !e.isCustomVisible
    }));
  }
  handleCustomPresetSelect(e) {
    typeof e.onSelect == "function" && e.onSelect(), this.handleSelect(e.startValue, e.endValue);
  }
  /**
   * Gets called when a preset has been selected.
   * @param {object} startValue - the start date (date or moment).
   * @param {object} endValue - the start date (date or moment).
   * @returns {undefined}
   */
  handleSelect(e, a) {
    const { onRangeChange: s, locale: i } = this.props, n = { isDropdownOpen: !1 };
    this.update(e, a, i, n, s);
  }
  /**
   * Gets called user clicks the apply button.
   * @returns {undefined}
   */
  handleCustomApply() {
    const { customRangeStartValue: e, customRangeEndValue: a, isStartValid: s, isEndValid: i } = this.state, { onRangeChange: n, locale: l } = this.props;
    if (s && i) {
      const d = { isDropdownOpen: !1 };
      this.update(e, a, l, d, n);
    }
  }
  getDropdownToggle(e) {
    const { children: a, clearable: s } = this.props, { startValueText: i, endValueText: n } = this.state, l = s && e.type !== S, d = p(l && "withClearButton"), r = a && typeof a == "function";
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        type: "button",
        className: "DateRangePickerToggle form-control dropdown-toggle text-left",
        "aria-haspopup": "true",
        "aria-expanded": "true",
        onClick: this.toggleDropdownOpen,
        ref: (u) => this.refDropdownToggle = u
      },
      r ? this.props.children(i, n) : /* @__PURE__ */ React.createElement("span", { className: d }, e),
      l && this.getClearButton(),
      /* @__PURE__ */ React.createElement("span", { className: "caret" })
    );
  }
  getClearButton() {
    return /* @__PURE__ */ React.createElement("span", { className: "clearButton", onClick: this.handleResetInternalState }, /* @__PURE__ */ React.createElement("span", { className: "clearButtonIcon rioglyph rioglyph-remove-sign" }));
  }
  getCustomPanelToggle(e, a) {
    return /* @__PURE__ */ React.createElement("li", { className: p("custom-panel-toggle", e && "hidden") }, /* @__PURE__ */ React.createElement("a", { role: "button", onClick: this.handleCustomToggle }, a, " ..."));
  }
  getCustomPanelButtons(e, a, s, i, n) {
    return /* @__PURE__ */ React.createElement("li", { className: p("custom-panel-buttons", "margin-20", !e && "hidden") }, /* @__PURE__ */ React.createElement("div", { className: "btn-toolbar" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: !a || !s,
        onClick: this.handleCustomApply,
        className: "btn btn-primary pull-right"
      },
      i
    ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: this.toggleDropdownOpen, className: "btn btn-default pull-right" }, n)));
  }
  render() {
    const {
      locale: e,
      textCustom: a,
      textApply: s,
      textCancel: i,
      textFrom: n,
      textTo: l,
      textToday: d,
      textLastWeek: r,
      textLastMonth: u,
      className: c,
      clearable: m,
      dropdownClass: g,
      dropdownMenuClass: N,
      customPresets: f,
      hasTimePicker: D
    } = this.props, {
      customRangeStartValue: k,
      customRangeEndValue: A,
      isStartValid: O,
      isEndValid: x,
      isCustomVisible: V,
      isDropdownOpen: M,
      dropdownToggleText: P
    } = this.state, v = this.isAutoDropActive() ? this.state.pullRight : this.props.pullRight, L = this.isAutoDropActive() ? this.state.dropup : this.props.dropup;
    f && _(f, w.customPresets) && (f[0].text = d, f[1].text = r, f[2].text = u);
    const B = p("DateRangePicker", c && c), F = p(
      "select",
      "dropdown",
      g,
      M && "open",
      L && "dropup"
    );
    return /* @__PURE__ */ React.createElement("div", { className: B }, /* @__PURE__ */ React.createElement("div", { className: F }, this.getDropdownToggle(P, m), /* @__PURE__ */ React.createElement(
      "ul",
      {
        className: p("dropdown-menu", v && "pull-right", N),
        ref: (h) => this.refDropdownMenu = h
      },
      f.map((h, I) => /* @__PURE__ */ React.createElement(
        "li",
        {
          key: `preset-${I}`,
          title: h.disabled && h.disabledText || null,
          className: p(h.disabled && "disabled")
        },
        /* @__PURE__ */ React.createElement(
          "a",
          {
            role: "button",
            className: p(V && "hidden"),
            onClick: h.disabled ? void 0 : this.handleCustomPresetSelect.bind(this, h)
          },
          h.text
        )
      )),
      /* @__PURE__ */ React.createElement("li", { role: "separator", className: p("divider", V && "hidden") }),
      this.getCustomPanelToggle(V, a),
      /* @__PURE__ */ React.createElement("li", { className: p("custom-panel", !V && "hidden") }, /* @__PURE__ */ React.createElement("div", { className: "row" }, /* @__PURE__ */ React.createElement("div", { className: "col-sm-6" }, /* @__PURE__ */ React.createElement("label", null, n), /* @__PURE__ */ React.createElement(
        y,
        {
          locale: e,
          open: !0,
          autoDropDirection: !1,
          dateFormat: !0,
          timeFormat: D,
          initialValue: k,
          onChange: this.onStartChange,
          closeOnSelect: !0,
          isValidDate: this.getValidStartDates,
          className: p("DatePicker", !O && "has-error")
        }
      )), /* @__PURE__ */ React.createElement("div", { className: "col-sm-6" }, /* @__PURE__ */ React.createElement("label", null, l), /* @__PURE__ */ React.createElement(
        y,
        {
          locale: e,
          open: !0,
          autoDropDirection: !1,
          dateFormat: !0,
          timeFormat: D,
          initialValue: A,
          onChange: this.onEndChange,
          closeOnSelect: !0,
          isValidDate: this.getValidEndDates,
          className: p("DatePicker", !x && "has-error")
        }
      )))),
      this.getCustomPanelButtons(V, O, x, s, i)
    )));
  }
}
E.propTypes = q;
E.defaultProps = w;
const ae = j(E);
export {
  E as DateRangePickerPure,
  ae as default
};
//# sourceMappingURL=DateRangePicker.js.map
