"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateRangePicker = void 0;

var _react = _interopRequireWildcard(require("react"));

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _reactDayPicker = _interopRequireWildcard(require("react-day-picker"));

var _reactIntl = require("react-intl");

var _card = require("../../core/structures/card");

var _popper = require("../../core/overlays/popper");

var _clickOutside = require("../../core/behaviors/click-outside");

var _unstyledButton = require("../../core/behaviors/unstyled-button");

var _index = require("../../mixins/branding/index");

var _dateRangePicker = require("./date-range-picker.css-rules");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var DateRangeButton = (0, _styledComponents["default"])(_unstyledButton.UnstyledButton).withConfig({
  displayName: "DateRangeButton",
  componentId: "w4445d-0"
})(["border:1px solid ", ";padding:10px;width:100%;text-align:center;"], (0, _index.getPaletteColor)('greyscale-light'));
var DayPickerContainer = (0, _styledComponents["default"])(_card.Card).withConfig({
  displayName: "DayPickerContainer",
  componentId: "w4445d-1"
})(["z-index:30;background-color:", ";margin-bottom:4px !important;margin-top:4px;", ""], (0, _index.getPaletteColor)('white'), _dateRangePicker.getDateRangePickerStyles);

function isSelectingFirstDay(from, to, day) {
  var isBeforeFirstDay = from && _reactDayPicker.DateUtils.isDayBefore(day, from);

  var isRangeSelected = from && to;
  return !from || isBeforeFirstDay || isRangeSelected;
}

function getDateCard(from, to, intl) {
  if (!from && !to) {
    return null;
  }

  if (from && !to) {
    return "".concat(intl.formatDate(from, {
      month: 'short',
      day: 'numeric'
    }), " -");
  }

  if (from && to) {
    if (_reactDayPicker.DateUtils.isSameDay(from, to)) {
      return intl.formatDate(from, {
        month: 'short',
        day: 'numeric'
      });
    }

    return "".concat(intl.formatDate(from, {
      month: 'short',
      day: 'numeric'
    }), " - ").concat(intl.formatDate(to, {
      month: 'short',
      day: 'numeric'
    }));
  }
}

var _DateRangePicker = function _DateRangePicker(_ref) {
  var _ref$range = _ref.range,
      from = _ref$range.from,
      to = _ref$range.to,
      placeholder = _ref.placeholder,
      onRangeChange = _ref.onRangeChange,
      _ref$hideAfterSelecti = _ref.hideAfterSelection,
      hideAfterSelection = _ref$hideAfterSelecti === void 0 ? false : _ref$hideAfterSelecti,
      className = _ref.className,
      dataQa = _ref['data-qa'],
      dataCy = _ref['data-cy'],
      id = _ref.id,
      intl = _ref.intl,
      props = _objectWithoutProperties(_ref, ["range", "placeholder", "onRangeChange", "hideAfterSelection", "className", "data-qa", "data-cy", "id", "intl"]);

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      isVisible = _useState2[0],
      setIsVisible = _useState2[1];

  var toggleDatePicker = (0, _react.useCallback)(function () {
    setIsVisible(function (vis) {
      return !vis;
    });
  }, []);
  var hideDatePicker = (0, _react.useCallback)(function () {
    setIsVisible(false);
  }, []); // Keep track of the last day for mouseEnter.

  var _useState3 = (0, _react.useState)(to),
      _useState4 = _slicedToArray(_useState3, 2),
      enteredTo = _useState4[0],
      setEnteredTo = _useState4[1];

  var memoizedIsSelectingFirstDay = (0, _react.useMemo)(function () {
    return function (day) {
      return isSelectingFirstDay(from, to, day);
    };
  }, [from, to]);
  var handleDayClick = (0, _react.useCallback)(function (day) {
    if (from && to && day >= from && day <= to) {
      onRangeChange({
        from: undefined,
        to: undefined
      });
      setEnteredTo(undefined);
    } else if (memoizedIsSelectingFirstDay(day)) {
      var convertedDate = new Date(day.setHours(0, 0, 0, 0)); // we set the from to the start of the day

      onRangeChange({
        from: convertedDate,
        to: undefined
      });
      setEnteredTo(undefined);
    } else {
      var _convertedDate = new Date(day.setHours(23, 59, 59, 999)); // set the from to the very end of the day


      if (hideAfterSelection) {
        hideDatePicker();
      }

      onRangeChange({
        from: from,
        to: _convertedDate
      });
      setEnteredTo(day);
    }
  }, [from, to, memoizedIsSelectingFirstDay, onRangeChange, hideAfterSelection, hideDatePicker]);
  var handleDayMouseEnter = (0, _react.useCallback)(function (day) {
    if (!memoizedIsSelectingFirstDay(day)) {
      setEnteredTo(day);
    }
  }, [memoizedIsSelectingFirstDay]);
  var cardDate = (0, _react.useMemo)(function () {
    return getDateCard(from, to, intl);
  }, [from, to, intl]) || placeholder;
  var modifiers = {
    start: from,
    end: enteredTo
  };
  var disabledDays = {
    before: from
  };
  var selectedDays = [from, {
    from: from,
    to: enteredTo
  }];
  return /*#__PURE__*/_react["default"].createElement(_clickOutside.ClickOutside, _extends({
    onClickOutside: hideDatePicker,
    "data-cy": dataCy,
    "data-qa": dataQa,
    id: id
  }, props), /*#__PURE__*/_react["default"].createElement(_popper.Popper, {
    reference: function reference(_ref2) {
      var referenceProps = _ref2.referenceProps,
          ref = _ref2.ref;
      return /*#__PURE__*/_react["default"].createElement(DateRangeButton, _extends({}, referenceProps, {
        ref: ref,
        borderRadius: 6,
        onClick: toggleDatePicker,
        className: className
      }), cardDate);
    },
    isVisible: isVisible,
    placement: "bottom"
  }, function (_ref3) {
    var ref = _ref3.ref,
        style = _ref3.style;
    return /*#__PURE__*/_react["default"].createElement(DayPickerContainer, {
      style: style,
      ref: ref
    }, /*#__PURE__*/_react["default"].createElement(_reactDayPicker["default"], {
      className: "Range",
      numberOfMonths: 2,
      selectedDays: selectedDays,
      disabledDays: disabledDays,
      modifiers: modifiers,
      onDayClick: handleDayClick,
      onDayMouseEnter: handleDayMouseEnter
    }));
  }));
};

var DateRangePicker = (0, _reactIntl.injectIntl)(_DateRangePicker);
exports.DateRangePicker = DateRangePicker;
DateRangePicker.displayName = 'DateRangePicker';