"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.toMoment = exports.DatePickerV2 = void 0;
var _react = _interopRequireWildcard(require("react"));
var _momentTimezone = _interopRequireDefault(require("moment-timezone"));
var _StylesV = require("./StylesV2");
var _Button = require("../Button");
var _IconButton = require("../IconButton");
var _Icons = require("../Icons");
var _Menu = require("../Menu");
var _Tooltip = require("../Tooltip");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var toMoment = exports.toMoment = function toMoment(date) {
  if (_momentTimezone.default.isMoment(date)) {
    return date;
  } else if (typeof date === "number") {
    return _momentTimezone.default.utc(date * 1000);
  } else if (typeof date === "string") {
    return _momentTimezone.default.utc(date);
  }
  return null;
};
var DatePickerV2 = exports.DatePickerV2 = function DatePickerV2(_ref) {
  var defaultSelected = _ref.selected,
    onChange = _ref.onChange,
    onSave = _ref.onSave,
    onClear = _ref.onClear,
    onClose = _ref.onClose,
    _ref$instant = _ref.instant,
    instant = _ref$instant === void 0 ? true : _ref$instant,
    target = _ref.target,
    _ref$mode = _ref.mode,
    mode = _ref$mode === void 0 ? "daily" : _ref$mode,
    _ref$saveLabel = _ref.saveLabel,
    saveLabel = _ref$saveLabel === void 0 ? "Save" : _ref$saveLabel,
    _ref$cancelLabel = _ref.cancelLabel,
    cancelLabel = _ref$cancelLabel === void 0 ? "Cancel" : _ref$cancelLabel,
    _ref$clearLabel = _ref.clearLabel,
    clearLabel = _ref$clearLabel === void 0 ? "Clear" : _ref$clearLabel,
    disabledDaysBefore = _ref.disabledDaysBefore,
    disabledDaysAfter = _ref.disabledDaysAfter,
    _ref$disabled = _ref.disabled,
    disabledDays = _ref$disabled === void 0 ? [] : _ref$disabled,
    modifiers = _ref.modifiers,
    disableAnimations = _ref.disableAnimations,
    _ref$firstDayOfWeek = _ref.firstDayOfWeek,
    firstDayOfWeek = _ref$firstDayOfWeek === void 0 ? 0 : _ref$firstDayOfWeek,
    forceClose = _ref.forceClose,
    required = _ref.required,
    month = _ref.month,
    disableYearPicker = _ref.disableYearPicker,
    _ref$position = _ref.position,
    position = _ref$position === void 0 ? "bottom-start" : _ref$position,
    menuClassName = _ref.menuClassName,
    popperClassName = _ref.popperClassName,
    _ref$enableConfirmMod = _ref.enableConfirmModal,
    enableConfirmModal = _ref$enableConfirmMod === void 0 ? false : _ref$enableConfirmMod,
    _ref$modalHeaderText = _ref.modalHeaderText,
    modalHeaderText = _ref$modalHeaderText === void 0 ? "Discard changes?" : _ref$modalHeaderText,
    _ref$modalDiscardMess = _ref.modalDiscardMessage,
    modalDiscardMessage = _ref$modalDiscardMess === void 0 ? "All unsaved changes will be lost." : _ref$modalDiscardMess,
    _ref$modalDiscardBtnT = _ref.modalDiscardBtnText,
    modalDiscardBtnText = _ref$modalDiscardBtnT === void 0 ? "OK" : _ref$modalDiscardBtnT,
    _ref$modalCancelBtnTe = _ref.modalCancelBtnText,
    modalCancelBtnText = _ref$modalCancelBtnTe === void 0 ? "Cancel" : _ref$modalCancelBtnTe,
    backgroundElementClass = _ref.backgroundElementClass,
    popperTooltipClassName = _ref.popperTooltipClassName,
    popperTooltipStyle = _ref.popperTooltipStyle,
    open = _ref.open,
    onCalendarToggle = _ref.onCalendarToggle,
    onDayClick = _ref.onDayClick,
    showControls = _ref.showControls;
  var _useState = (0, _react.useState)(open),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isYearSelectOpen = _useState4[0],
    setIsYearSelectOpen = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = _slicedToArray(_useState5, 2),
    showDiscardModal = _useState6[0],
    setShowDiscardModal = _useState6[1];
  var _useState7 = (0, _react.useState)(mode === "monthly" || mode === "quarterly"),
    _useState8 = _slicedToArray(_useState7, 2),
    isMonthSelectOpen = _useState8[0],
    setIsMonthSelectOpen = _useState8[1];
  var _useState9 = (0, _react.useState)(null),
    _useState10 = _slicedToArray(_useState9, 2),
    monthTransitionDirection = _useState10[0],
    setMonthTransitionDirection = _useState10[1];
  var _useState11 = (0, _react.useState)(function () {
      if (defaultSelected && defaultSelected.from) {
        return toMoment(defaultSelected.from);
      }
      if (month) {
        return toMoment(month);
      }
      return _momentTimezone.default.utc();
    }),
    _useState12 = _slicedToArray(_useState11, 2),
    currentDate = _useState12[0],
    setCurrentDate = _useState12[1];
  var _useState13 = (0, _react.useState)(function () {
      if (defaultSelected && defaultSelected.from) {
        return toMoment(defaultSelected.from);
      } else if (month) {
        return toMoment(month);
      }
      return _momentTimezone.default.utc();
    }),
    _useState14 = _slicedToArray(_useState13, 2),
    targetDate = _useState14[0],
    setTargetDate = _useState14[1];
  var _useState15 = (0, _react.useState)(function () {
      if (!defaultSelected) {
        return null;
      }
      if (!defaultSelected.from) {
        return null;
      }
      return {
        from: toMoment(defaultSelected.from),
        to: defaultSelected.to ? toMoment(defaultSelected.to) : null
      };
    }),
    _useState16 = _slicedToArray(_useState15, 2),
    selected = _useState16[0],
    setSelected = _useState16[1];
  var _useState17 = (0, _react.useState)(null),
    _useState18 = _slicedToArray(_useState17, 2),
    hoveredDate = _useState18[0],
    setHoveredDate = _useState18[1];
  var timezone = _momentTimezone.default.defaultZone ? _momentTimezone.default.defaultZone.name : _momentTimezone.default.tz.guess();
  var currentDateInTimezone = (0, _momentTimezone.default)().tz(timezone).format("YYYY-MM-DD");
  var today = _momentTimezone.default.utc(currentDateInTimezone);
  var selectedYearRef = (0, _react.useRef)(null);
  var datePickerRef = (0, _react.useRef)(null);
  var handleSelection = (0, _react.useCallback)(function (range) {
    if (!range) {
      setSelected(null);
      if (onChange) onChange(undefined);
      if (instant && onSave) {
        onSave(undefined);
      }
    } else {
      setSelected(range);
      if (onChange) onChange({
        from: range.from.utc().unix(),
        to: (0, _momentTimezone.default)(range.to).utc().unix()
      });
      if (instant && onSave) {
        onSave({
          from: range.from.utc().unix(),
          to: (0, _momentTimezone.default)(range.to).utc().unix()
        });
      }
    }
  }, [onChange, onSave, instant]);
  var toggleCalendar = (0, _react.useCallback)(function () {
    setIsOpen(!isOpen);
    if (onCalendarToggle) onCalendarToggle(!isOpen);
  }, [isOpen, onCalendarToggle]);
  var toggleYearSelect = (0, _react.useCallback)(function () {
    setIsYearSelectOpen(!isYearSelectOpen);
    setIsMonthSelectOpen(true);
  }, [isYearSelectOpen]);
  var toggleMonthSelect = (0, _react.useCallback)(function () {
    if (mode !== "monthly" && mode !== "quarterly") {
      setIsMonthSelectOpen(!isMonthSelectOpen);
    }
  }, [isMonthSelectOpen, mode]);
  (0, _react.useEffect)(function () {
    if (defaultSelected && defaultSelected.from) {
      setSelected({
        from: toMoment(defaultSelected.from),
        to: defaultSelected.to ? toMoment(defaultSelected.to) : null
      });
      setCurrentDate(toMoment(defaultSelected.from) || _momentTimezone.default.utc());
      setTargetDate(toMoment(defaultSelected.from) || _momentTimezone.default.utc());
    } else {
      setSelected(null);
    }
  }, [defaultSelected, month]);
  var handleDateSelect = function handleDateSelect(date) {
    var isSameMonth = date.isSame(currentDate, "month");
    if (isSameMonth || disableAnimations) {
      setCurrentDate(date);
      setTargetDate(date);
    } else {
      var direction = date.isBefore(currentDate, "month") ? "prev" : "next";
      setTargetDate(date);
      setMonthTransitionDirection(direction);
    }
    switch (mode) {
      case "daily":
        handleDailySelection(date);
        break;
      case "weekly":
        handleWeeklySelection(date);
        break;
      case "custom":
        handleCustomSelection(date);
        break;
      default:
        console.warn("Unhandled mode: ".concat(mode));
    }
    if (instant && mode !== "custom" && forceClose) toggleCalendar();
  };
  var handleDailySelection = function handleDailySelection(date) {
    if (!date.isSame(selected === null || selected === void 0 ? void 0 : selected.from)) {
      handleSelection({
        from: date,
        to: date
      });
    } else if (!required) {
      handleSelection(undefined);
    }
  };
  var handleWeeklySelection = function handleWeeklySelection(date) {
    var _selected$from;
    var currentDayOfWeek = date.day();
    var daysToSubtract = (currentDayOfWeek - firstDayOfWeek + 7) % 7;
    var startOfWeek = date.clone().subtract(daysToSubtract, "days").startOf("day");
    var endOfWeek = startOfWeek.clone().add(6, "days");
    if (!startOfWeek.isSame(selected === null || selected === void 0 || (_selected$from = selected.from) === null || _selected$from === void 0 ? void 0 : _selected$from.startOf("day"))) {
      handleSelection({
        from: startOfWeek,
        to: endOfWeek
      });
    } else if (!required) {
      handleSelection(undefined);
    }
  };
  var handleCustomSelection = function handleCustomSelection(date) {
    if (!selected || (selected === null || selected === void 0 ? void 0 : selected.from) === _momentTimezone.default.utc(Number(defaultSelected === null || defaultSelected === void 0 ? void 0 : defaultSelected.from) * 1000)) {
      setSelected({
        from: date.utc(),
        to: null
      });
      onChange && onChange({
        from: date.utc().unix(),
        to: date.utc().unix()
      });
      return;
    }
    if (_momentTimezone.default.isMoment(selected === null || selected === void 0 ? void 0 : selected.from) && !(selected !== null && selected !== void 0 && selected.to) && !(selected !== null && selected !== void 0 && selected.from.isSame(date.utc(), "day"))) {
      var newSelection = selected !== null && selected !== void 0 && selected.from.isBefore(date) ? {
        from: selected.from,
        to: date.utc()
      } : {
        from: date.utc(),
        to: selected.from
      };
      setSelected(newSelection);
      onChange && onChange({
        from: newSelection.from.utc().unix(),
        to: newSelection.to.utc().unix()
      });
    } else if (_momentTimezone.default.isMoment(selected === null || selected === void 0 ? void 0 : selected.from) && _momentTimezone.default.isMoment(selected === null || selected === void 0 ? void 0 : selected.to)) {
      setSelected({
        from: date.utc(),
        to: null
      });
      onChange && onChange({
        from: date.utc().unix(),
        to: null
      });
    } else if (_momentTimezone.default.isMoment(selected === null || selected === void 0 ? void 0 : selected.from) && selected !== null && selected !== void 0 && selected.from.isSame(date.utc(), "day") && !required) {
      setSelected(null);
      onChange && onChange(undefined);
    } else if (selected.from === null && selected.to === null) {
      setSelected({
        from: date.utc(),
        to: null
      });
      onChange && onChange({
        from: date.utc().unix(),
        to: date.utc().unix()
      });
    }
  };
  var handleSave = function handleSave() {
    if (onSave) {
      toggleCalendar();
      if (mode === "custom" && !(selected !== null && selected !== void 0 && selected.to)) {
        setSelected({
          from: _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from),
          to: _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from)
        });
      }
      if (selected) {
        onSave({
          from: _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from).unix(),
          to: selected !== null && selected !== void 0 && selected.to ? _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.to).unix() : _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from).unix()
        });
      } else {
        if (!required) {
          onSave(undefined);
          setCurrentDate(_momentTimezone.default.utc());
          setTargetDate(_momentTimezone.default.utc());
        }
      }
    }
  };
  var handleMonthChange = (0, _react.useCallback)(function (direction) {
    setMonthTransitionDirection(direction);
    if (isMonthSelectOpen) {
      setTargetDate(function (prevDate) {
        if (prevDate) {
          return direction === "prev" ? prevDate.clone().subtract(1, "year") : prevDate.clone().add(1, "year");
        }
        return prevDate;
      });
      if (disableAnimations) {
        setCurrentDate(function (prevDate) {
          return direction === "prev" ? prevDate.clone().subtract(1, "year") : prevDate.clone().add(1, "year");
        });
      }
    } else {
      setTargetDate(function (prevDate) {
        if (prevDate) {
          return direction === "prev" ? prevDate.clone().subtract(1, "month") : prevDate.clone().add(1, "month");
        }
        return prevDate;
      });
      if (disableAnimations) {
        setCurrentDate(function (prevDate) {
          return direction === "prev" ? prevDate.clone().subtract(1, "month") : prevDate.clone().add(1, "month");
        });
      }
    }
  }, [disableAnimations, isMonthSelectOpen]);
  var onAnimationEnd = function onAnimationEnd() {
    if (targetDate) {
      setCurrentDate(targetDate);
      setMonthTransitionDirection(null);
    }
  };
  var handleYearSelect = function handleYearSelect(year) {
    setCurrentDate(currentDate.clone().year(year));
    setTargetDate(currentDate.clone().year(year));
    setIsYearSelectOpen(false);
    setIsMonthSelectOpen(true);
  };
  var handleMonthSelect = function handleMonthSelect(month) {
    var newDate = currentDate.clone().utc().month(month);
    setCurrentDate(newDate);
    setTargetDate(newDate);
    if (mode === "monthly") {
      var _selected$to;
      var _range = {
        from: newDate.clone().startOf("month"),
        to: newDate.clone().endOf("month").startOf("day")
      };
      var isSameMonth = (selected === null || selected === void 0 ? void 0 : selected.from.isSame(_range.from, "month")) && (selected === null || selected === void 0 || (_selected$to = selected.to) === null || _selected$to === void 0 ? void 0 : _selected$to.isSame(_range.to, "month"));
      if (isSameMonth) {
        if (!required) {
          handleSelection(undefined);
          if (instant && onSave) {
            setCurrentDate(_momentTimezone.default.utc());
            setTargetDate(_momentTimezone.default.utc());
          }
        }
      } else {
        handleSelection(_range);
      }
    }
    if (mode === "quarterly") {
      var _selected$to2;
      var quarterRange = {
        from: newDate.clone().startOf("quarter"),
        to: newDate.clone().endOf("quarter").startOf("day")
      };
      var isSameQuarter = (selected === null || selected === void 0 ? void 0 : selected.from.isSame(quarterRange.from, "quarter")) && (selected === null || selected === void 0 || (_selected$to2 = selected.to) === null || _selected$to2 === void 0 ? void 0 : _selected$to2.isSame(quarterRange.to, "quarter"));
      if (isSameQuarter) {
        if (!required) {
          handleSelection(undefined);
          if (instant && onSave) {
            setCurrentDate(_momentTimezone.default.utc());
            setTargetDate(_momentTimezone.default.utc());
          }
        }
      } else {
        handleSelection(quarterRange);
      }
    }
    if (mode !== "monthly" && mode !== "quarterly") {
      setIsMonthSelectOpen(false);
    }
    if (instant && (mode === "monthly" || mode === "quarterly") && forceClose) toggleCalendar();
  };
  (0, _react.useEffect)(function () {
    if (isYearSelectOpen && selectedYearRef.current) {
      var _selectedYearRef$curr;
      selectedYearRef === null || selectedYearRef === void 0 || (_selectedYearRef$curr = selectedYearRef.current) === null || _selectedYearRef$curr === void 0 || _selectedYearRef$curr.scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    }
  }, [isYearSelectOpen]);
  var renderDaysOfWeek = function renderDaysOfWeek() {
    var daysOfWeek = _momentTimezone.default.weekdaysShort();
    var orderedDays = [...daysOfWeek.slice(firstDayOfWeek), ...daysOfWeek.slice(0, firstDayOfWeek)];
    return orderedDays.map(function (day) {
      return /*#__PURE__*/_react.default.createElement(_StylesV.StyledDayName, {
        key: day
      }, day[0]);
    });
  };
  var animationClass = (0, _react.useMemo)(function () {
    return monthTransitionDirection && !disableAnimations ? monthTransitionDirection === "next" ? "slide-down" : "slide-up" : "";
  }, [disableAnimations, monthTransitionDirection]);
  var handleDayClick = function handleDayClick(day, modifiers) {
    handleDateSelect(day);
    if (onDayClick) onDayClick(day, modifiers);
  };
  var getHoverRange = function getHoverRange() {
    if (!hoveredDate) return null;
    if (mode === "quarterly") {
      var startMonth = hoveredDate.clone().startOf("quarter");
      var endMonth = hoveredDate.clone().endOf("quarter");
      return {
        from: startMonth,
        to: endMonth
      };
    }
    if (mode === "weekly") {
      var currentDayOfWeek = hoveredDate.day();
      var daysToSubtract = (currentDayOfWeek - firstDayOfWeek + 7) % 7;
      var startOfWeek = hoveredDate.clone().subtract(daysToSubtract, "days").startOf("day");
      var endOfWeek = startOfWeek.clone().add(6, "days");
      return {
        from: startOfWeek,
        to: endOfWeek
      };
    }
    if (mode === "custom" && selected !== null && selected !== void 0 && selected.from && !(selected !== null && selected !== void 0 && selected.to)) {
      var from = selected.from.isBefore(hoveredDate) ? selected.from : hoveredDate;
      var to = selected.from.isAfter(hoveredDate) ? selected.from : hoveredDate;
      return {
        from,
        to
      };
    }
    return null;
  };
  var renderCalendarDates = function renderCalendarDates() {
    var startOfMonth = currentDate.clone().startOf("month");
    var startDate = startOfMonth.clone().isoWeekday(firstDayOfWeek);
    var endDate = startDate.clone().add(6, "weeks");
    var date = startDate.clone();
    var dates = [];
    var hoverRange = getHoverRange();
    var _loop = function _loop() {
      var clonedDate = date.clone();
      var isToday = clonedDate.isSame(today, "day");
      var isSelected = selected && (clonedDate.isBetween(selected.from, selected.to, "day", "[]") || clonedDate.isSame(selected.from, "day") || clonedDate.isSame(selected.to, "day"));
      var isHovered = hoverRange && (mode === "weekly" || mode === "custom") && clonedDate.isBetween(hoverRange.from, hoverRange.to, "day", "[]");
      var isDisabled = disabledDaysBefore && clonedDate.isBefore(disabledDaysBefore, "day") || disabledDaysAfter && clonedDate.isAfter(disabledDaysAfter, "day") || disabledDays.includes(clonedDate.day());
      var modifierClasses = [];
      var modifierTitles = [];
      var titles;
      if (modifiers) Object.keys(modifiers || {}).forEach(function (modifier) {
        var _modifiers$modifier = modifiers[modifier](clonedDate.toDate()),
          matched = _modifiers$modifier.matched,
          title = _modifiers$modifier.title;
        if (matched) {
          modifierClasses.push(modifier);
          if (title) modifierTitles.push(title);
        }
      });
      if (modifierTitles.length) {
        titles = /*#__PURE__*/_react.default.createElement("div", {
          key: "title-wrapper-".concat(clonedDate.toString())
        }, modifierTitles.map(function (title, index) {
          return /*#__PURE__*/_react.default.createElement("div", {
            key: "title-text-".concat(index)
          }, title);
        }));
      }
      var isOutside = !clonedDate.isSame(currentDate, "month");
      dates.push( /*#__PURE__*/_react.default.createElement(_Tooltip.Tooltip, {
        title: titles,
        disable: !modifierTitles.length,
        key: clonedDate.toString(),
        popperTooltipClassName: popperTooltipClassName,
        popperTooltipStyle: popperTooltipStyle
      }, /*#__PURE__*/_react.default.createElement(_StylesV.StyledCalendarDate, {
        className: "".concat(isSelected ? "selected" : "", " ").concat(isToday ? "today-day" : "", "\n          ").concat(isDisabled ? "disabled" : "", " ").concat(isHovered ? "hovered" : "", " ").concat(modifierClasses.join(" "), "\n          ").concat(isOutside ? "outside" : ""),
        onClick: function onClick() {
          return handleDayClick(clonedDate, modifierClasses);
        },
        onMouseEnter: mode === "weekly" || mode === "custom" ? function () {
          return setHoveredDate(clonedDate);
        } : undefined,
        onMouseLeave: mode === "weekly" || mode === "custom" ? function () {
          return setHoveredDate(null);
        } : undefined
      }, clonedDate.date())));
      date.add(1, "day");
    };
    while (date.isBefore(endDate)) {
      _loop();
    }
    return dates;
  };
  var renderYearSelect = function renderYearSelect() {
    var years = Array.from({
      length: 200
    }, function (_, i) {
      return 1900 + i;
    });
    return /*#__PURE__*/_react.default.createElement(_StylesV.StyledYearSelect, null, years.map(function (year) {
      var isSelected = selected && ((selected === null || selected === void 0 ? void 0 : selected.to) && year >= selected.from.year() && year <= selected.to.year() || year === selected.from.year() || (selected === null || selected === void 0 ? void 0 : selected.to) && year === selected.to.year());
      var isDisabledYear = disabledDaysBefore && year < disabledDaysBefore.year() || disabledDaysAfter && year > disabledDaysAfter.year();
      return /*#__PURE__*/_react.default.createElement(_StylesV.StyledYearOption, {
        key: year,
        ref: year === currentDate.year() ? selectedYearRef : null,
        className: "".concat(isSelected ? "selected" : "", " ").concat(year === today.year() ? "today-year" : "", " ").concat(isDisabledYear ? "disabled" : ""),
        onClick: function onClick() {
          return handleYearSelect(year);
        }
      }, year);
    }));
  };
  var renderMonthSelect = function renderMonthSelect() {
    var months = _momentTimezone.default.months();
    var hoverRange = getHoverRange();
    return /*#__PURE__*/_react.default.createElement(_StylesV.StyledMonthSelect, null, months.map(function (month, index) {
      var monthDate = currentDate.clone().month(index);
      var isSelected = selected && (monthDate.isBetween(selected.from, selected.to, "month", "[]") || monthDate.isSame(selected.from, "month") || monthDate.isSame(selected.to, "month"));
      var isDisabledMonth = disabledDaysBefore && monthDate.isBefore(disabledDaysBefore, "month") || disabledDaysAfter && monthDate.isAfter(disabledDaysAfter, "month");
      var isHoveredQuarter = hoverRange && mode === "quarterly" && monthDate.isBetween(hoverRange.from, hoverRange.to, "month", "[]");
      return /*#__PURE__*/_react.default.createElement(_StylesV.StyledMonthOption, {
        key: month,
        className: "".concat(isSelected ? "selected" : "", " ").concat(index === today.month() && currentDate.year() === today.year() ? "today-month" : "", " ").concat(isDisabledMonth ? "disabled" : "", " ").concat(isHoveredQuarter ? "hovered" : ""),
        onClick: function onClick() {
          return handleMonthSelect(index);
        },
        onMouseEnter: mode === "quarterly" ? function () {
          return setHoveredDate(monthDate);
        } : undefined,
        onMouseLeave: mode === "quarterly" ? function () {
          return setHoveredDate(null);
        } : undefined
      }, month.substring(0, 3));
    }));
  };
  var captionText = (0, _react.useMemo)(function () {
    var isCurrentYear = currentDate.isSame(today, "year");
    return !isMonthSelectOpen && !isYearSelectOpen ? "".concat(currentDate.format("MMMM")).concat(isCurrentYear ? "" : " ".concat(currentDate.format("YYYY"))) : currentDate.format("YYYY");
  }, [currentDate, isMonthSelectOpen, isYearSelectOpen, today]);
  var handleClear = (0, _react.useCallback)(function () {
    if (typeof onClear === "function") onClear();
    handleSelection(undefined);
  }, [handleSelection, onClear]);
  var handleClose = (0, _react.useCallback)(function () {
    var _selected$to3;
    if (mode === "custom" && instant && selected) {
      setSelected({
        from: _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from),
        to: selected !== null && selected !== void 0 && selected.to ? _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.to) : _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from)
      });
    }
    if (instant && onSave && mode === "custom" && selected && (!(selected !== null && selected !== void 0 && selected.from.isSame(_momentTimezone.default.utc(Number(defaultSelected === null || defaultSelected === void 0 ? void 0 : defaultSelected.from) * 1000))) || !(selected !== null && selected !== void 0 && (_selected$to3 = selected.to) !== null && _selected$to3 !== void 0 && _selected$to3.isSame(_momentTimezone.default.utc(Number(defaultSelected === null || defaultSelected === void 0 ? void 0 : defaultSelected.to) * 1000))))) {
      onSave({
        from: _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from).unix(),
        to: selected !== null && selected !== void 0 && selected.to ? _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.to).unix() : _momentTimezone.default.utc(selected === null || selected === void 0 ? void 0 : selected.from).unix()
      });
    }
    if (mode === "custom" && instant && !selected && onSave) {
      onSave(undefined);
    }
    setCurrentDate(defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.from ? toMoment(defaultSelected.from) : month ? toMoment(month) : _momentTimezone.default.utc());
    setTargetDate(defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.from ? toMoment(defaultSelected.from) : month ? toMoment(month) : _momentTimezone.default.utc());
    setSelected(defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.from ? {
      from: toMoment(defaultSelected.from),
      to: defaultSelected.to ? toMoment(defaultSelected.to) : null
    } : null);
    toggleCalendar();
    setIsYearSelectOpen(false);
    setIsMonthSelectOpen(mode === "monthly" || mode === "quarterly");
    setMonthTransitionDirection(null);
    if (typeof onClose === "function") onClose();
  }, [defaultSelected, instant, mode, month, onClose, onSave, selected, toggleCalendar]);
  var handleBeforeClose = (0, _react.useCallback)(function () {
    var shouldClose = true;
    if (!target || !enableConfirmModal || instant || required) {
      shouldClose = true;
    }
    if (target && enableConfirmModal && !instant && !required && (selected && !defaultSelected || !selected && defaultSelected || selected !== null && selected !== void 0 && selected.from && defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.from && !selected.from.isSame(toMoment(defaultSelected.from)) || selected !== null && selected !== void 0 && selected.to && defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.to && !selected.to.isSame(toMoment(defaultSelected.to)))) {
      shouldClose = false;
      setShowDiscardModal(true);
    }
    if (shouldClose) handleClose();
    return shouldClose;
  }, [defaultSelected, enableConfirmModal, handleClose, instant, required, selected, target]);
  var Wrapper = target ? _Menu.Menu : "div";
  var handleCaptionClick = (0, _react.useCallback)(function () {
    isMonthSelectOpen && !disableYearPicker ? toggleYearSelect() : toggleMonthSelect();
  }, [disableYearPicker, isMonthSelectOpen, toggleMonthSelect, toggleYearSelect]);
  var handleCloseDiscardModal = (0, _react.useCallback)(function () {
    setShowDiscardModal(false);
  }, []);
  var handleSaveDiscardModal = (0, _react.useCallback)(function () {
    setSelected(defaultSelected !== null && defaultSelected !== void 0 && defaultSelected.from ? {
      from: toMoment(defaultSelected.from),
      to: defaultSelected.to ? toMoment(defaultSelected.to) : null
    } : null);
    setShowDiscardModal(false);
    handleClose();
  }, [defaultSelected, handleClose]);
  var wrapperProps = target ? {
    className: "c-date-picker--calendar",
    target,
    onBeforeClose: handleBeforeClose,
    onClose: handleClose,
    open: isOpen,
    active: isOpen,
    onOpen: toggleCalendar,
    position,
    menuClassName,
    popperClassName,
    backgroundElementClass
  } : {
    className: "c-date-picker--calendar"
  };
  (0, _react.useEffect)(function () {
    var handleKeyDown = function handleKeyDown(event) {
      if (event.key === "ArrowRight") {
        handleMonthChange("next");
      } else if (event.key === "ArrowLeft") {
        handleMonthChange("prev");
      }
    };
    if (isOpen) {
      window.addEventListener("keydown", handleKeyDown);
    } else {
      window.removeEventListener("keydown", handleKeyDown);
    }
    return function () {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, handleMonthChange]);
  var saveIsDisabled = function saveIsDisabled() {
    if (!defaultSelected && !selected) {
      return true;
    }
    if (defaultSelected && selected && defaultSelected.from && selected.from.isSame(toMoment(defaultSelected.from)) && defaultSelected.to && selected.to && selected.to.isSame(toMoment(defaultSelected.to))) {
      return true;
    }
    return false;
  };
  return /*#__PURE__*/_react.default.createElement(_StylesV.StyledDatePickerWrapper, {
    ref: datePickerRef
  }, /*#__PURE__*/_react.default.createElement(Wrapper, wrapperProps, /*#__PURE__*/_react.default.createElement(_StylesV.StyledDatePickerContainerInner, null, /*#__PURE__*/_react.default.createElement(_StylesV.StyledCalendarHeader, null, isYearSelectOpen ? null : /*#__PURE__*/_react.default.createElement(_IconButton.IconButton, {
    onClick: function onClick() {
      return handleMonthChange("prev");
    },
    variant: "text gray",
    size: "small"
  }, /*#__PURE__*/_react.default.createElement(_Icons.ArrowLeftIcon, null)), /*#__PURE__*/_react.default.createElement(_StylesV.StyledCaption, {
    className: "".concat(animationClass, " ").concat(isYearSelectOpen ? "year-caption" : ""),
    key: isMonthSelectOpen ? currentDate.year() : currentDate.month(),
    onClick: handleCaptionClick,
    onAnimationEnd: onAnimationEnd
  }, captionText), isYearSelectOpen ? null : /*#__PURE__*/_react.default.createElement(_IconButton.IconButton, {
    onClick: function onClick() {
      return handleMonthChange("next");
    },
    variant: "text gray",
    size: "small"
  }, /*#__PURE__*/_react.default.createElement(_Icons.ArrowRightIcon, null))), /*#__PURE__*/_react.default.createElement(_StylesV.StyledCalendarSelector, null, isYearSelectOpen ? renderYearSelect() : isMonthSelectOpen ? /*#__PURE__*/_react.default.createElement(_StylesV.StyledMonthSelector, {
    className: animationClass,
    key: currentDate.year(),
    onAnimationEnd: onAnimationEnd
  }, renderMonthSelect()) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_StylesV.StyledDaysOfWeek, null, renderDaysOfWeek()), /*#__PURE__*/_react.default.createElement(_StylesV.StyledCalendarDates, {
    className: animationClass,
    key: currentDate.month()
  }, renderCalendarDates()))), (target || showControls) && (!instant ? /*#__PURE__*/_react.default.createElement(_StylesV.StyledControls, null, /*#__PURE__*/_react.default.createElement(_StylesV.StyledControlsLeft, null, /*#__PURE__*/_react.default.createElement(_Button.Button, {
    size: "small",
    variant: "primary",
    onClick: handleSave,
    disabled: saveIsDisabled()
  }, saveLabel), /*#__PURE__*/_react.default.createElement(_Tooltip.Tooltip, {
    title: cancelLabel,
    popperTooltipStyle: {
      zIndex: 1301
    }
  }, /*#__PURE__*/_react.default.createElement(_IconButton.IconButton, {
    size: "small",
    variant: "text gray",
    onClick: handleBeforeClose
  }, /*#__PURE__*/_react.default.createElement(_Icons.CancelCrossIcon, null)))), !required ? /*#__PURE__*/_react.default.createElement(_Button.Button, {
    size: "small",
    onClick: handleClear,
    variant: "text gray"
  }, clearLabel) : null) : !required ? /*#__PURE__*/_react.default.createElement(_StylesV.StyledControls, null, /*#__PURE__*/_react.default.createElement(_StylesV.StyledClearInstantButton, {
    size: "small",
    onClick: handleClear,
    variant: "text gray"
  }, clearLabel)) : null))), !instant && target && !required && enableConfirmModal ? /*#__PURE__*/_react.default.createElement(_StylesV.StyledConfirmDialog, {
    className: "modal-select-date",
    open: showDiscardModal,
    onCancel: handleCloseDiscardModal,
    onConfirm: handleSaveDiscardModal,
    dialogTitle: modalHeaderText,
    dialogContent: modalDiscardMessage,
    cancelBtnText: modalCancelBtnText,
    confirmBtnText: modalDiscardBtnText
  }) : null);
};
//# sourceMappingURL=DatePickerV2.js.map