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; }
import { useCallback, useEffect, useState } from 'react';
import { useIntl } from 'react-intl';
import { addMonths, isBefore, isSameDay, isWithinInterval, setDate, setMonth, setYear, startOfDay, subMilliseconds, subMonths, format } from 'date-fns';
import { usePrevious } from '../../../../common/Hooks';
import { getDateFormat, getLocale, parseDateString } from '../../shared/dateUtils';
import { INPUT_ID_START, INPUT_ID_RANGE } from '../../shared/constants';
var formatInputValue = function formatInputValue(selectedDate, dateFormat, locale) {
  if (selectedDate) {
    return format(selectedDate, dateFormat, {
      locale: locale
    });
  }
  return '';
};
var handleSelectDate = function handleSelectDate(date, selectedDate, selectedEndDate, allowSingleDayRange, isRangePicker) {
  if (!selectedDate || !isRangePicker) return [date, null];
  if (isBefore(date, selectedDate)) return [date, selectedEndDate];
  var swapDate = !selectedEndDate && isBefore(date, selectedDate);
  if (swapDate) return [date, selectedDate];
  if (isSameDay(date, selectedDate)) {
    if (!allowSingleDayRange) {
      return [selectedDate, null];
    }
    return [selectedDate, selectedDate];
  }
  if (selectedEndDate && isSameDay(date, selectedEndDate)) {
    if (!allowSingleDayRange) {
      return [selectedDate, null];
    }
    return [selectedEndDate, selectedEndDate];
  }
  return [selectedDate, date];
};
export var useDatePickerClearable = function useDatePickerClearable(_ref) {
  var id = _ref.id,
    selectedDateProp = _ref.selectedDateProp,
    enableDate = _ref.enableDate,
    disableDate = _ref.disableDate,
    onChange = _ref.onChange,
    onBlur = _ref.onBlur,
    allowDateUpdateOnType = _ref.allowDateUpdateOnType,
    _ref$allowSingleDayRa = _ref.allowSingleDayRange,
    allowSingleDayRange = _ref$allowSingleDayRa === void 0 ? true : _ref$allowSingleDayRa,
    _ref$noOfMonthsInCale = _ref.noOfMonthsInCalendarView,
    dateRange = _ref$noOfMonthsInCale === void 0 ? 1 : _ref$noOfMonthsInCale;
  var _useIntl = useIntl(),
    locale = _useIntl.locale;
  var _useState = useState(selectedDateProp || null),
    _useState2 = _slicedToArray(_useState, 2),
    selectedDate = _useState2[0],
    setSelectedDate = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    invalidDate = _useState4[0],
    setInvalidDate = _useState4[1];
  var _useState5 = useState(formatInputValue(selectedDate, getDateFormat(locale), getLocale(locale))),
    _useState6 = _slicedToArray(_useState5, 2),
    inputValue = _useState6[0],
    setInputValue = _useState6[1];
  var _useState7 = useState(setDate(selectedDateProp && new Date(selectedDateProp) || startOfDay(new Date()), 1)),
    _useState8 = _slicedToArray(_useState7, 2),
    viewedDate = _useState8[0],
    setViewedDate = _useState8[1];
  var previousInputValue = usePrevious(inputValue);
  useEffect(function () {
    if (selectedDateProp) {
      setSelectedDate(selectedDateProp);
      var controlledInputValue = formatInputValue(selectedDateProp, getDateFormat(locale), getLocale(locale));
      setInputValue(controlledInputValue);
      setViewedDate(setDate(selectedDateProp, 1));
    }
  }, [locale, selectedDateProp]);
  useEffect(function () {
    if (previousInputValue && !inputValue) {
      setSelectedDate(null);
    }
    setInvalidDate(false);
  }, [inputValue, previousInputValue]);
  var allowedDate = useCallback(function (date) {
    if (date && disableDate && disableDate(date)) {
      setInvalidDate(true);
      return null;
    }
    if (date && enableDate && !enableDate(date)) {
      setInvalidDate(true);
      return null;
    }
    return date;
  }, [disableDate, enableDate]);
  var handleDateClick = useCallback(function (date) {
    var _handleSelectDate = handleSelectDate(date, selectedDate, null, allowSingleDayRange, false),
      _handleSelectDate2 = _slicedToArray(_handleSelectDate, 1),
      startDate = _handleSelectDate2[0];
    if (selectedDate && isSameDay(startDate, selectedDate)) return;
    var dateString = formatInputValue(startDate, getDateFormat(locale), getLocale(locale));
    setSelectedDate(startDate);
    setInputValue(dateString);
    if (onChange) onChange(startDate);
  }, [selectedDate, allowSingleDayRange, locale, onChange]);
  var onDateClick = useCallback(function (date) {
    if (date && !isWithinInterval(date, {
      start: viewedDate,
      end: subMilliseconds(addMonths(viewedDate, dateRange), 1)
    })) {
      var newViewedDate = isBefore(date, viewedDate) ? subMonths(viewedDate, 1) : addMonths(viewedDate, 1);
      setViewedDate(newViewedDate);
    }
    handleDateClick(date);
  }, [viewedDate, dateRange, handleDateClick]);
  var handleInputSubmit = useCallback(function () {
    var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [],
      _ref3 = _slicedToArray(_ref2, 1),
      _ref3$ = _ref3[0],
      startDateValue = _ref3$ === void 0 ? inputValue : _ref3$;
    var _ref4 = [parseDateString(startDateValue, locale)],
      parsedStartDate = _ref4[0];
    var _ref5 = [allowedDate(parsedStartDate)],
      startDate = _ref5[0];
    if (startDate) {
      setSelectedDate(startDate);
      if (startDate && !isWithinInterval(startDate, {
        start: viewedDate,
        end: subMilliseconds(addMonths(viewedDate, dateRange), 1)
      })) {
        setViewedDate(setDate(startDate, 1));
      }
      var dateString = formatInputValue(startDate, getDateFormat(locale), getLocale(locale));
      setInputValue(dateString);
      if (onChange) onChange(startDate);
      if (onBlur) onBlur(startDate);
    }
  }, [inputValue, locale, allowedDate, viewedDate, dateRange, onChange, onBlur]);
  var onMonthChange = useCallback(function (index) {
    setViewedDate(setMonth(viewedDate, index));
  }, [viewedDate, setViewedDate]);
  var onYearChange = useCallback(function (year) {
    setViewedDate(setYear(viewedDate, year));
  }, [viewedDate, setViewedDate]);
  var handleInputOnChange = useCallback(function (event) {
    var _event$target = event.target,
      value = _event$target.value,
      elementId = _event$target.id;
    if (value === '' && onChange) {
      setInputValue(value);
      onChange(undefined);
      return;
    }
    var assignedValues = function () {
      if (elementId === INPUT_ID_START(id)) {
        setInputValue(value);
        return [value];
      }
      if (elementId === INPUT_ID_RANGE(id)) {
        var _value$split$map = value.split('-').map(function (v) {
            return v.trim();
          }),
          _value$split$map2 = _slicedToArray(_value$split$map, 1),
          startDateValue = _value$split$map2[0];
        setInputValue(startDateValue);
        return [startDateValue];
      }
      setInputValue(value);
      return [value];
    }();
    if (allowDateUpdateOnType) {
      handleInputSubmit(assignedValues);
    }
  }, [allowDateUpdateOnType, handleInputSubmit, id, onChange]);
  var handleInputOnBlur = useCallback(function () {
    handleInputSubmit();
  }, [handleInputSubmit]);
  var handleInputKeyDown = useCallback(function (event) {
    if (event.key === 'Enter') handleInputSubmit();
  }, [handleInputSubmit]);
  var clearDate = useCallback(function () {
    setInputValue('');
  }, []);
  return {
    selectedDate: selectedDate,
    inputValue: inputValue,
    handleInputKeyDown: handleInputKeyDown,
    handleInputOnChange: handleInputOnChange,
    handleInputOnBlur: handleInputOnBlur,
    onMonthChange: onMonthChange,
    onYearChange: onYearChange,
    onDateClick: onDateClick,
    viewedDate: viewedDate,
    clearDate: clearDate,
    invalidDate: invalidDate
  };
};