"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateStepper = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _momentTimezone = _interopRequireDefault(require("moment-timezone"));
var _Styles = require("./Styles");
var _DatePicker = require("../../DatePicker/DatePicker");
var _Icons = require("../../Icons");
var _ArrowLeft = _interopRequireDefault(require("../../Icons/collection/ArrowLeft"));
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; }
/**
 * This component allow you to select date range. It accepts two parameters "from" and "to" as valid format
 * onChange and onBack and onForward it will return "from: Date" and "to: Date" as function arguments
 */

var DateStepper = exports.DateStepper = function DateStepper(_ref) {
  var step = _ref.step,
    formatCallback = _ref.formatCallback,
    onChange = _ref.onChange,
    from = _ref.from,
    to = _ref.to,
    onBack = _ref.onBack,
    onForward = _ref.onForward,
    minValue = _ref.minValue,
    maxValue = _ref.maxValue,
    className = _ref.className,
    _ref$period = _ref.period,
    period = _ref$period === void 0 ? "week" : _ref$period,
    _ref$withDatePicker = _ref.withDatePicker,
    withDatePicker = _ref$withDatePicker === void 0 ? true : _ref$withDatePicker,
    _ref$defaultMonth = _ref.defaultMonth,
    defaultMonth = _ref$defaultMonth === void 0 ? (0, _momentTimezone.default)() : _ref$defaultMonth,
    enableYearPicker = _ref.enableYearPicker,
    _ref$position = _ref.position,
    position = _ref$position === void 0 ? "bottom" : _ref$position,
    popperClassName = _ref.popperClassName,
    _ref$mode = _ref.mode,
    mode = _ref$mode === void 0 ? "outlined" : _ref$mode,
    _ref$alwaysShowDate = _ref.alwaysShowDate,
    alwaysShowDate = _ref$alwaysShowDate === void 0 ? false : _ref$alwaysShowDate;
  var _useState = (0, _react.useState)(_momentTimezone.default.utc(from)),
    _useState2 = _slicedToArray(_useState, 2),
    fromDate = _useState2[0],
    setFromDate = _useState2[1];
  var _useState3 = (0, _react.useState)(_momentTimezone.default.utc(to)),
    _useState4 = _slicedToArray(_useState3, 2),
    toDate = _useState4[0],
    setToDate = _useState4[1];
  var getDatesByPeriod = (0, _react.useCallback)(function (interval) {
    var date = fromDate ? fromDate : (0, _momentTimezone.default)();
    if (step === "daily") {
      date.add(interval, "days");
      return [date, date.clone()];
    } else if (step === "weekly") {
      date.add(interval, "weeks");
      return [date.clone().startOf(period), date.clone().endOf(period)];
    } else if (step === "monthly") {
      date.add(interval, "months");
      return [date.clone().startOf("month"), date.clone().endOf("month")];
    } else if (step === "quarterly") {
      date.add(interval, "quarters");
      return [date.clone().startOf("quarter"), date.clone().endOf("quarter")];
    } else if (step === "yearly") {
      date.add(interval, "years");
      return [date.clone().startOf("year"), date.clone().endOf("year")];
    }
    return [date, date];
  }, [fromDate, period, step]);
  var getDateFormatted = (0, _react.useMemo)(function () {
    if (formatCallback) {
      return formatCallback(fromDate, toDate);
    }
    var actualYear = (0, _momentTimezone.default)().year();
    var showWeekOrCustomDateFormat = function showWeekOrCustomDateFormat(start, end) {
      if (start.year() === actualYear && end.year() === actualYear) {
        return start.utc().format("MMM DD") + " - " + end.utc().format("MMM DD");
      } else {
        return start.utc().format("MMM DD YYYY") + " - " + end.utc().format("MMM DD YYYY");
      }
    };
    if (step === "daily") {
      if (fromDate.year() === actualYear) {
        return fromDate.utc().format("MMM DD");
      }
      return fromDate.utc().format("MMM DD YYYY");
    } else if (step === "weekly") {
      var startDate = fromDate.clone().utc().startOf(period);
      var endDate = startDate.clone().utc().endOf(period);
      return showWeekOrCustomDateFormat(startDate, endDate);
    } else if (step === "monthly") {
      return fromDate.utc().format("MMM YYYY");
    } else if (step === "quarterly") {
      return "Q".concat(fromDate.utc().quarter(), "/").concat(fromDate.utc().format("YYYY"));
    } else if (step === "yearly") {
      return fromDate.utc().format("YYYY");
    } else if (step === "range") {
      return showWeekOrCustomDateFormat(fromDate, toDate);
    }
    return "";
  }, [fromDate, toDate, step, formatCallback, period]);
  var datePickerMode = (0, _react.useMemo)(function () {
    if (step === "range") return "custom";
    if (step === "yearly") return "custom";
    return step;
  }, [step]);
  var onDatePickerChange = (0, _react.useCallback)(function (dates) {
    var fromDateTemp = _momentTimezone.default.utc(Number(dates === null || dates === void 0 ? void 0 : dates.from) * 1000);
    var toDateTemp = _momentTimezone.default.utc(Number(dates === null || dates === void 0 ? void 0 : dates.to) * 1000);
    setFromDate(fromDateTemp);
    setToDate(toDateTemp);
    if (onChange && _momentTimezone.default.isMoment(fromDateTemp) && _momentTimezone.default.isMoment(toDateTemp)) {
      onChange(fromDateTemp.toDate(), toDateTemp.toDate());
    }
  }, [onChange, setFromDate, setToDate]);
  var isAfterMaxDate = (0, _react.useMemo)(function () {
    return _momentTimezone.default.isMoment(maxValue) && (0, _momentTimezone.default)(_momentTimezone.default.utc(maxValue).format("YYYY-MM-DD")).isSameOrBefore(toDate.utc().format("YYYY-MM-DD"));
  }, [maxValue, toDate]);
  var isBeforeMinDate = (0, _react.useMemo)(function () {
    return _momentTimezone.default.isMoment(minValue) && _momentTimezone.default.utc(_momentTimezone.default.utc(minValue).format("YYYY-MM-DD")).isSameOrAfter(toDate.utc().format("YYYY-MM-DD"));
  }, [minValue, toDate]);
  (0, _react.useEffect)(function () {
    if (isBeforeMinDate) {
      if (step === "daily") {
        setFromDate(_momentTimezone.default.utc(minValue));
        setToDate(_momentTimezone.default.utc(minValue));
      }
    }
    if (isAfterMaxDate) {
      if (step === "daily") {
        setFromDate(_momentTimezone.default.utc(maxValue));
        setToDate(_momentTimezone.default.utc(maxValue));
      }
    }
  }, [step, minValue, maxValue, isBeforeMinDate, isAfterMaxDate]);
  var onRightClickHandler = (0, _react.useCallback)(function () {
    if (isAfterMaxDate) {
      return;
    }
    var _getDatesByPeriod = getDatesByPeriod(1),
      _getDatesByPeriod2 = _slicedToArray(_getDatesByPeriod, 2),
      newFrom = _getDatesByPeriod2[0],
      newTo = _getDatesByPeriod2[1];
    setFromDate(_momentTimezone.default.utc(newFrom));
    setToDate(_momentTimezone.default.utc(newTo));
    if (onChange) {
      onChange(_momentTimezone.default.utc(newFrom), _momentTimezone.default.utc(newTo));
    }
    if (onForward) {
      onForward(_momentTimezone.default.utc(newFrom).toDate(), _momentTimezone.default.utc(newTo).toDate());
    }
  }, [isAfterMaxDate, getDatesByPeriod, onChange, onForward]);
  var onLeftClickHandler = (0, _react.useCallback)(function () {
    if (isBeforeMinDate) {
      return;
    }
    var _getDatesByPeriod3 = getDatesByPeriod(-1),
      _getDatesByPeriod4 = _slicedToArray(_getDatesByPeriod3, 2),
      newFrom = _getDatesByPeriod4[0],
      newTo = _getDatesByPeriod4[1];
    setFromDate(_momentTimezone.default.utc(newFrom));
    setToDate(_momentTimezone.default.utc(newTo));
    if (onChange) {
      onChange(_momentTimezone.default.utc(newFrom), _momentTimezone.default.utc(newTo));
    }
    if (onBack) {
      onBack(_momentTimezone.default.utc(newFrom).toDate(), _momentTimezone.default.utc(newTo).toDate());
    }
  }, [isBeforeMinDate, getDatesByPeriod, onChange, onBack]);
  var renderLeftRightButtons = (0, _react.useMemo)(function () {
    return step !== "range";
  }, [step]);
  (0, _react.useEffect)(function () {
    setFromDate(_momentTimezone.default.utc(from));
    setToDate(_momentTimezone.default.utc(to));
  }, [from, to]);
  var dateStepperWidth = function dateStepperWidth(fromDay, toDay, range) {
    if (fromDay.utc().year() !== _momentTimezone.default.utc().year() || toDay.utc().year() !== _momentTimezone.default.utc().year()) {
      switch (range) {
        case "daily":
        case "monthly":
          return {
            minWidth: "122px"
          };
        case "weekly":
        case "custom":
          return {
            minWidth: "232px"
          };
      }
    }
    switch (range) {
      case "monthly":
        return {
          minWidth: "122px"
        };
      case "weekly":
      case "custom":
        return {
          minWidth: "182px"
        };
    }
    return {
      minWidth: "102px"
    };
  };
  var isDisabled = (0, _react.useCallback)(function (day) {
    var dayFormat = _momentTimezone.default.utc(day).format("YYYY-MM-DD");
    var isBefore = _momentTimezone.default.isMoment(maxValue) && (0, _momentTimezone.default)(_momentTimezone.default.utc(maxValue).format("YYYY-MM-DD")).isBefore(dayFormat);
    var isAfter = _momentTimezone.default.isMoment(minValue) && (0, _momentTimezone.default)(_momentTimezone.default.utc(minValue).format("YYYY-MM-DD")).isAfter(dayFormat);
    return isBefore || isAfter;
  }, [maxValue, minValue]);
  var modifiers = (0, _react.useMemo)(function () {
    return {
      disabled: function disabled(day) {
        return {
          matched: isDisabled(day),
          title: null
        };
      },
      nonWorkingDay: function nonWorkingDay(day) {
        return {
          matched: isDisabled(day),
          title: null
        };
      }
    };
  }, [isDisabled]);
  return /*#__PURE__*/_react.default.createElement(_Styles.StyledButtonGroup, {
    className: (0, _classnames.default)("c-date-stepper", className)
  }, renderLeftRightButtons ? /*#__PURE__*/_react.default.createElement(_Styles.StyledControl, {
    type: "button",
    variant: mode === "flat" ? "text gray" : "secondary",
    onClick: onLeftClickHandler,
    disabled: isBeforeMinDate
  }, /*#__PURE__*/_react.default.createElement(_ArrowLeft.default, null)) : null, /*#__PURE__*/_react.default.createElement(_Styles.StyledDiv, {
    $isTargetable: step === "yearly" || !withDatePicker,
    $isRounded: step === "range",
    $mode: mode,
    $alwaysShowDate: alwaysShowDate,
    style: dateStepperWidth(fromDate, toDate, step)
  }, withDatePicker && step !== "yearly" ? /*#__PURE__*/_react.default.createElement(_DatePicker.DatePicker, {
    month: defaultMonth,
    target: /*#__PURE__*/_react.default.createElement(_Styles.StyledButton, {
      type: "button"
    }, getDateFormatted),
    mode: datePickerMode,
    selected: {
      from: _momentTimezone.default.utc(fromDate).unix(),
      to: _momentTimezone.default.utc(toDate).unix()
    },
    onChange: onDatePickerChange,
    firstDayOfWeek: period === "week" ? 0 : 1,
    modifiers: modifiers,
    disabledDaysAfter: maxValue,
    disabledDaysBefore: minValue,
    disableYearPicker: !enableYearPicker,
    popperClassName: popperClassName,
    position: position,
    key: datePickerMode,
    instant: true,
    required: true
  }) : /*#__PURE__*/_react.default.createElement(_Styles.StyledSpan, null, getDateFormatted)), renderLeftRightButtons ? /*#__PURE__*/_react.default.createElement(_Styles.StyledControl, {
    type: "button",
    variant: mode === "flat" ? "text gray" : "secondary",
    onClick: onRightClickHandler,
    disabled: isAfterMaxDate
  }, /*#__PURE__*/_react.default.createElement(_Icons.ArrowRightIcon, null)) : null);
};
DateStepper.displayName = "DateStepper";
//# sourceMappingURL=DateStepper.js.map