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 '../dateUtils';
import { INPUT_ID_START, INPUT_ID_END, INPUT_ID_RANGE } from '../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 useDatePicker = function useDatePicker(_ref) {
  var id = _ref.id,
    selectedDateProp = _ref.selectedDateProp,
    selectedEndDateProp = _ref.selectedEndDateProp,
    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,
    _ref$isRangePicker = _ref.isRangePicker,
    isRangePicker = _ref$isRangePicker === void 0 ? false : _ref$isRangePicker;
  var _useIntl = useIntl(),
    locale = _useIntl.locale;
  var _useState = useState(selectedDateProp || null),
    _useState2 = _slicedToArray(_useState, 2),
    selectedDate = _useState2[0],
    setSelectedDate = _useState2[1];
  var _useState3 = useState(selectedEndDateProp || null),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedEndDate = _useState4[0],
    setSelectedEndDate = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    invalidDate = _useState6[0],
    setInvalidDate = _useState6[1];
  var _useState7 = useState(formatInputValue(selectedDate, getDateFormat(locale), getLocale(locale))),
    _useState8 = _slicedToArray(_useState7, 2),
    inputValue = _useState8[0],
    setInputValue = _useState8[1];
  var _useState9 = useState(formatInputValue(selectedEndDate, getDateFormat(locale), getLocale(locale))),
    _useState10 = _slicedToArray(_useState9, 2),
    inputValueEnd = _useState10[0],
    setInputValueEnd = _useState10[1];
  var _useState11 = useState(setDate(selectedDateProp && new Date(selectedDateProp) || startOfDay(new Date()), 1)),
    _useState12 = _slicedToArray(_useState11, 2),
    viewedDate = _useState12[0],
    setViewedDate = _useState12[1];
  var previousInputValue = usePrevious(inputValue);
  var previousInputValueEnd = usePrevious(inputValueEnd);
  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 (selectedEndDateProp) {
      setSelectedEndDate(selectedEndDateProp);
      var controlledInputValueEnd = formatInputValue(selectedEndDateProp, getDateFormat(locale), getLocale(locale));
      setInputValueEnd(controlledInputValueEnd);
    }
  }, [locale, selectedEndDateProp]);
  useEffect(function () {
    if (previousInputValue && !inputValue) {
      setSelectedDate(null);
    }
    if (previousInputValueEnd && !inputValueEnd) {
      setSelectedEndDate(null);
    }
    setInvalidDate(false);
  }, [inputValue, inputValueEnd, previousInputValue, previousInputValueEnd]);
  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, selectedEndDate, allowSingleDayRange, isRangePicker),
      _handleSelectDate2 = _slicedToArray(_handleSelectDate, 2),
      startDate = _handleSelectDate2[0],
      endDate = _handleSelectDate2[1];
    if (selectedDate && isSameDay(startDate, selectedDate) && endDate && selectedEndDate && isSameDay(endDate, selectedEndDate)) return;
    var dateString = formatInputValue(startDate, getDateFormat(locale), getLocale(locale));
    var dateStringEnd = formatInputValue(endDate, getDateFormat(locale), getLocale(locale));
    setSelectedDate(startDate);
    setSelectedEndDate(endDate);
    setInputValue(dateString);
    setInputValueEnd(dateStringEnd);
    if (onChange) onChange(startDate, endDate);
  }, [selectedDate, selectedEndDate, allowSingleDayRange, isRangePicker, 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, 2),
      _ref3$ = _ref3[0],
      startDateValue = _ref3$ === void 0 ? inputValue : _ref3$,
      _ref3$2 = _ref3[1],
      endDateValue = _ref3$2 === void 0 ? inputValueEnd : _ref3$2;
    var _ref4 = [parseDateString(startDateValue, locale), parseDateString(endDateValue, locale)],
      parsedStartDate = _ref4[0],
      parsedEndDate = _ref4[1];
    var _ref5 = [allowedDate(parsedStartDate), allowedDate(parsedEndDate)],
      startDate = _ref5[0],
      endDate = _ref5[1];
    if (!allowSingleDayRange && startDate && endDate && isSameDay(startDate, endDate)) return;
    if (startDate) {
      var selectedDatesReselected = function () {
        if (startDate && !endDate) {
          return selectedDate && isSameDay(startDate, selectedDate);
        }
        if (startDate && endDate) {
          return selectedDate && selectedEndDate && isSameDay(startDate, selectedDate) && isSameDay(endDate, selectedEndDate);
        }
        return false;
      }();
      if (selectedDatesReselected) return;
      setSelectedDate(startDate);
      setSelectedEndDate(endDate);
      if (startDate && !endDate && !isWithinInterval(startDate, {
        start: viewedDate,
        end: subMilliseconds(addMonths(viewedDate, dateRange), 1)
      })) {
        setViewedDate(setDate(startDate, 1));
      }
      if (startDate && endDate && !isWithinInterval(endDate, {
        start: viewedDate,
        end: subMilliseconds(addMonths(viewedDate, dateRange), 1)
      })) {
        setViewedDate(setDate(endDate, 1));
      }
      var dateString = formatInputValue(startDate, getDateFormat(locale), getLocale(locale));
      var dateStringEnd = formatInputValue(endDate, getDateFormat(locale), getLocale(locale));
      setInputValue(dateString);
      setInputValueEnd(dateStringEnd);
      if (onChange) onChange(startDate, endDate);
      if (onBlur) onBlur(startDate, endDate);
    }
  }, [inputValue, inputValueEnd, locale, allowedDate, allowSingleDayRange, viewedDate, dateRange, onChange, onBlur, selectedDate, selectedEndDate]);
  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;
    var assignedValues = function () {
      if (elementId === INPUT_ID_START(id)) {
        setInputValue(value);
        return [value];
      }
      if (elementId === INPUT_ID_END(id)) {
        setInputValueEnd(value);
        return [undefined, 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, 2),
          startDateValue = _value$split$map2[0],
          endDateValue = _value$split$map2[1];
        setInputValue(startDateValue);
        setInputValueEnd(endDateValue);
        return [startDateValue, endDateValue];
      }
      setInputValue(value);
      return [value];
    }();
    if (allowDateUpdateOnType) {
      handleInputSubmit(assignedValues);
    }
  }, [allowDateUpdateOnType, handleInputSubmit, id]);
  var handleInputOnBlur = useCallback(function () {
    handleInputSubmit();
  }, [handleInputSubmit]);
  var handleInputKeyDown = useCallback(function (event) {
    if (event.key === 'Enter') handleInputSubmit();
  }, [handleInputSubmit]);
  var clearDate = useCallback(function () {
    setInputValue('');
    setInputValueEnd('');
  }, []);
  return {
    selectedDate: selectedDate,
    selectedEndDate: selectedEndDate,
    inputValue: inputValue,
    inputValueEnd: inputValueEnd,
    handleInputKeyDown: handleInputKeyDown,
    handleInputOnChange: handleInputOnChange,
    handleInputOnBlur: handleInputOnBlur,
    onMonthChange: onMonthChange,
    onYearChange: onYearChange,
    onDateClick: onDateClick,
    viewedDate: viewedDate,
    clearDate: clearDate,
    invalidDate: invalidDate
  };
};