function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["className", "endDate", "format", "id", "isDisabled", "isInvalid", "isRange", "label", "onChange", "onCalendarFocus", "startDate", "initialIsOpen", "disabledDays", "initialMonth", "initialStartDate", "initialEndDate", "placement", "onBlur", "today", "value"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) 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; }
import { IconEvent } from '@defencedigital/icon-library';
import FocusTrap from 'focus-trap-react';
import React, { useCallback, useRef, useState } from 'react';
import { DayPickerProps } from 'react-day-picker';
import { DATE_FORMAT } from '../../constants';
import { WEEKDAY_TITLES } from './constants';
import { DATEPICKER_ACTION } from './types';
import { hasClass } from '../../helpers';
import { InlineButton } from '../InlineButtons/InlineButton';
import { isDateValid } from './utils';
import { StyledLabel } from '../TextInput/partials/StyledLabel';
import { StyledDatePickerInput } from './partials/StyledDatePickerInput';
import { StyledDayPicker } from './partials/StyledDayPicker';
import { StyledFloatingBox } from './partials/StyledFloatingBox';
import { StyledInlineButtons } from '../InlineButtons/partials/StyledInlineButtons';
import { StyledInput } from '../TextInput/partials/StyledInput';
import { StyledInputWrapper } from './partials/StyledInputWrapper';
import { StyledOuterWrapper } from './partials/StyledOuterWrapper';
import { useExternalId } from '../../hooks/useExternalId';
import { useFocus } from '../../hooks/useFocus';
import { useFocusTrapOptions } from './useFocusTrapOptions';
import { useHandleDayClick } from './useHandleDayClick';
import { useInput } from './useInput';
import { useRangeHoverOrFocusDate } from './useRangeHoverOrFocusDate';
import { useStatefulRef } from '../../hooks/useStatefulRef';
import { useDatePickerReducer } from './useDatePickerReducer';
var replaceInvalidDate = function replaceInvalidDate(date) {
  return isDateValid(date) ? date : undefined;
};
export var DatePicker = function DatePicker(_ref) {
  var className = _ref.className,
    externalEndDate = _ref.endDate,
    _ref$format = _ref.format,
    datePickerFormat = _ref$format === void 0 ? DATE_FORMAT.SHORT : _ref$format,
    externalId = _ref.id,
    _ref$isDisabled = _ref.isDisabled,
    isDisabled = _ref$isDisabled === void 0 ? false : _ref$isDisabled,
    isInvalid = _ref.isInvalid,
    _ref$isRange = _ref.isRange,
    isRange = _ref$isRange === void 0 ? false : _ref$isRange,
    _ref$label = _ref.label,
    label = _ref$label === void 0 ? 'Date' : _ref$label,
    onChange = _ref.onChange,
    onCalendarFocus = _ref.onCalendarFocus,
    externalStartDate = _ref.startDate,
    _ref$initialIsOpen = _ref.initialIsOpen,
    initialIsOpen = _ref$initialIsOpen === void 0 ? false : _ref$initialIsOpen,
    disabledDays = _ref.disabledDays,
    initialMonth = _ref.initialMonth,
    _ref$initialStartDate = _ref.initialStartDate,
    initialStartDate = _ref$initialStartDate === void 0 ? null : _ref$initialStartDate,
    _ref$initialEndDate = _ref.initialEndDate,
    initialEndDate = _ref$initialEndDate === void 0 ? null : _ref$initialEndDate,
    _ref$placement = _ref.placement,
    placement = _ref$placement === void 0 ? 'bottom-start' : _ref$placement,
    _onBlur = _ref.onBlur,
    today = _ref.today,
    _ = _ref.value,
    rest = _objectWithoutProperties(_ref, _excluded);
  var id = useExternalId(externalId);
  var titleId = useExternalId('datepicker-title');
  var floatingBoxId = useExternalId('datepicker-contentId');
  var buttonRef = useRef(null);
  var inputRef = useRef(null);
  var _useFocus = useFocus(),
    hasFocus = _useFocus.hasFocus,
    onLocalBlur = _useFocus.onLocalBlur,
    onLocalFocus = _useFocus.onLocalFocus;
  var _useState = useState(initialIsOpen),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var close = useCallback(function () {
    return setIsOpen(false);
  }, []);
  var toggleIsOpen = useCallback(function () {
    return setIsOpen(function (previousIsOpen) {
      return !previousIsOpen;
    });
  }, []);
  var focusTrapOptions = useFocusTrapOptions(close, isRange ? [buttonRef, inputRef] : [buttonRef]);
  var _useDatePickerReducer = useDatePickerReducer(externalStartDate, externalEndDate, initialStartDate, initialEndDate, datePickerFormat, isRange),
    _useDatePickerReducer2 = _slicedToArray(_useDatePickerReducer, 2),
    state = _useDatePickerReducer2[0],
    dispatch = _useDatePickerReducer2[1];
  var handleDayClick = useHandleDayClick(state, dispatch, isRange, disabledDays, onChange);
  var startDate = state.startDate,
    endDate = state.endDate;
  var hasError = state.hasError || isInvalid || hasClass(className, 'is-invalid');
  var _useStatefulRef = useStatefulRef(),
    _useStatefulRef2 = _slicedToArray(_useStatefulRef, 2),
    floatingBoxTarget = _useStatefulRef2[0],
    setFloatingBoxTarget = _useStatefulRef2[1];
  var _useRangeHoverOrFocus = useRangeHoverOrFocusDate(isRange),
    rangeHoverOrFocusDate = _useRangeHoverOrFocus.rangeHoverOrFocusDate,
    handleDayFocus = _useRangeHoverOrFocus.handleDayFocus,
    handleDayMouseEnter = _useRangeHoverOrFocus.handleDayMouseEnter,
    handleDayMouseLeave = _useRangeHoverOrFocus.handleDayMouseLeave;
  var _useInput = useInput(datePickerFormat, isRange, handleDayClick, dispatch),
    handleKeyDown = _useInput.handleKeyDown,
    handleInputBlur = _useInput.handleInputBlur,
    handleInputChange = _useInput.handleInputChange;
  var modifiers = _objectSpread({
    start: replaceInvalidDate(startDate),
    end: replaceInvalidDate(endDate)
  }, today ? {
    today: today
  } : {});
  var hasContent = Boolean(startDate);
  var placeholder = !isRange ? datePickerFormat.toLowerCase() : undefined;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledDatePickerInput, {
    className: className,
    $isDisabled: isDisabled,
    ref: setFloatingBoxTarget
  }, /*#__PURE__*/React.createElement(StyledOuterWrapper, {
    $hasFocus: hasFocus && !isRange,
    $isInvalid: hasError,
    $isDisabled: isDisabled
  }, /*#__PURE__*/React.createElement(StyledInputWrapper, {
    $isRange: isRange
  }, /*#__PURE__*/React.createElement(StyledLabel, {
    id: titleId,
    $hasFocus: hasFocus && !isRange,
    $hasContent: hasContent,
    htmlFor: id
  }, label, placeholder && " (".concat(placeholder, ")")), /*#__PURE__*/React.createElement(StyledInput, _extends({
    ref: inputRef,
    $hasLabel: Boolean(label),
    "aria-label": "Choose date",
    id: id,
    type: "text",
    disabled: isDisabled,
    readOnly: isRange,
    onChange: handleInputChange,
    onKeyDown: handleKeyDown,
    onBlur: function onBlur(e) {
      onLocalBlur(e);
      handleInputBlur();
      if (_onBlur) {
        _onBlur(e);
      }
    },
    onFocus: function onFocus() {
      onLocalFocus();
      if (isRange) {
        var _buttonRef$current;
        (_buttonRef$current = buttonRef.current) === null || _buttonRef$current === void 0 ? void 0 : _buttonRef$current.focus();
      }
    },
    onClick: function onClick() {
      if (isRange) {
        toggleIsOpen();
      }
    },
    placeholder: placeholder,
    value: state.inputValue
  }, rest))), /*#__PURE__*/React.createElement(StyledInlineButtons, null, /*#__PURE__*/React.createElement(InlineButton, {
    "aria-expanded": isOpen,
    "aria-label": "".concat(isOpen ? 'Hide' : 'Show', " day picker"),
    "aria-owns": floatingBoxId,
    isDisabled: isDisabled,
    onClick: toggleIsOpen,
    ref: buttonRef
  }, /*#__PURE__*/React.createElement(IconEvent, {
    size: 18
  }))))), /*#__PURE__*/React.createElement(StyledFloatingBox, {
    id: floatingBoxId,
    isVisible: isOpen,
    placement: placement,
    targetElement: floatingBoxTarget,
    role: "dialog",
    "aria-modal": true,
    "aria-labelledby": titleId,
    "aria-live": "polite"
  }, /*#__PURE__*/React.createElement(FocusTrap, {
    focusTrapOptions: focusTrapOptions
  }, /*#__PURE__*/React.createElement(StyledDayPicker, {
    firstDayOfWeek: 1,
    weekdaysShort: WEEKDAY_TITLES,
    selectedDays: [{
      from: replaceInvalidDate(startDate),
      to: replaceInvalidDate(endDate) || rangeHoverOrFocusDate
    }],
    modifiers: modifiers,
    onDayClick: function onDayClick(day, _ref2) {
      var disabled = _ref2.disabled;
      if (disabled) {
        return;
      }
      var newState = handleDayClick(day);
      dispatch({
        type: DATEPICKER_ACTION.REFRESH_HAS_ERROR
      });
      dispatch({
        type: DATEPICKER_ACTION.REFRESH_INPUT_VALUE
      });
      if (newState.endDate || !isRange) {
        setTimeout(function () {
          return close();
        });
      }
    },
    initialMonth: replaceInvalidDate(startDate) || initialMonth,
    disabledDays: disabledDays,
    $isRange: isRange,
    $isVisible: isOpen,
    onFocus: onCalendarFocus,
    onDayMouseEnter: handleDayMouseEnter,
    onDayMouseLeave: handleDayMouseLeave,
    onDayFocus: handleDayFocus
  }))));
};
DatePicker.displayName = 'DatePicker';