import _pt from "prop-types";
var _excluded = ["className", "onChange", "defaultMonth", "fromDate", "fromMonth", "fromYear", "toDate", "toMonth", "toYear"];

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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; }

import React, { useRef, useState } from 'react';
import CalendarIcon from '../Icons/CalendarIcon';
import CustomDayPicker from './CustomDayPicker';
import classNames from 'classnames';
import isMatch from 'date-fns/isMatch';
import useLabelMask from '../TextField/useLabelMask';
import useClickOutsideHandler from '../utilities/useClickOutsideHandler';
import usePressEscapeHandler from '../utilities/usePressEscapeHandler';
import { DATE_MASK } from '../TextField/useLabelMask';
import { FormLabel, useFormLabel } from '../FormLabel';
import { TextInput } from '../TextField';
import { t } from '../i18n';

var SingleInputDateField = function SingleInputDateField(props) {
  var className = props.className,
      onChange = props.onChange,
      defaultMonth = props.defaultMonth,
      fromDate = props.fromDate,
      fromMonth = props.fromMonth,
      fromYear = props.fromYear,
      toDate = props.toDate,
      toMonth = props.toMonth,
      toYear = props.toYear,
      remainingProps = _objectWithoutProperties(props, _excluded);

  var withPicker = (fromDate != null || fromMonth != null || Number.isInteger(fromYear)) && (toDate != null || toMonth != null || Number.isInteger(toYear));

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      pickerVisible = _useState2[0],
      setPickerVisible = _useState2[1]; // Set up change handlers


  function handleInputChange(event) {
    var updatedValue = event.currentTarget.value;
    onChange(updatedValue, DATE_MASK(updatedValue, true));
  }

  function handlePickerChange(date) {
    var _inputRef$current;

    var updatedValue = "".concat(date.getMonth() + 1, "/").concat(date.getDate(), "/").concat(date.getFullYear());
    onChange(DATE_MASK(updatedValue), DATE_MASK(updatedValue, true));
    setPickerVisible(false);
    (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.focus();
  } // Collect all the props and elements for the input and its labels


  var _useFormLabel = useFormLabel(_objectSpread(_objectSpread({}, remainingProps), {}, {
    className: classNames('ds-c-single-input-date-field', {
      'ds-c-single-input-date-field--with-picker': withPicker
    }, className),
    labelComponent: 'label',
    wrapperIsFieldset: false
  })),
      labelProps = _useFormLabel.labelProps,
      fieldProps = _useFormLabel.fieldProps,
      wrapperProps = _useFormLabel.wrapperProps,
      bottomError = _useFormLabel.bottomError;

  var inputRef = useRef();

  var _useLabelMask = useLabelMask(DATE_MASK, _objectSpread(_objectSpread({}, fieldProps), {}, {
    onChange: handleInputChange,
    type: 'text',
    setRef: function setRef(el) {
      inputRef.current = el;
    }
  })),
      labelMask = _useLabelMask.labelMask,
      inputProps = _useLabelMask.inputProps; // Handle alternate ways of closing the day picker


  var dayPickerRef = useRef();
  var calendarButtonRef = useRef();
  useClickOutsideHandler([dayPickerRef, calendarButtonRef], function () {
    return setPickerVisible(false);
  });
  usePressEscapeHandler(dayPickerRef, function () {
    var _inputRef$current2;

    setPickerVisible(false);
    (_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 ? void 0 : _inputRef$current2.focus();
  }); // Validate the date string (value) and make date null if it's invalid. We don't want to pass
  // a bizarre date to DayPicker like `new Date('01/02')`, which is interpreted as `Jan 02, 2001`

  var dateString = DATE_MASK(props.value, true);
  var validDateString = isMatch(dateString, 'MM/dd/yyyy');
  var date = validDateString ? new Date(dateString) : null;
  return /*#__PURE__*/React.createElement("div", wrapperProps, /*#__PURE__*/React.createElement(FormLabel, labelProps), labelMask, /*#__PURE__*/React.createElement("div", {
    className: "ds-c-single-input-date-field__field-wrapper"
  }, /*#__PURE__*/React.createElement(TextInput, inputProps), withPicker && /*#__PURE__*/React.createElement("button", {
    className: "ds-c-single-input-date-field__button",
    onClick: function onClick() {
      return setPickerVisible(!pickerVisible);
    },
    ref: calendarButtonRef
  }, /*#__PURE__*/React.createElement(CalendarIcon, {
    ariaHidden: false,
    title: t(pickerVisible ? 'singleInputDateField.close' : 'singleInputDateField.open')
  }))), pickerVisible && /*#__PURE__*/React.createElement("div", {
    ref: dayPickerRef,
    role: "dialog"
  }, /*#__PURE__*/React.createElement(CustomDayPicker, {
    selected: date,
    onSelect: handlePickerChange,
    defaultMonth: date !== null && date !== void 0 ? date : defaultMonth,
    fromDate: fromDate,
    fromMonth: fromMonth,
    fromYear: fromYear,
    toDate: toDate,
    toMonth: toMonth,
    toYear: toYear
  })), bottomError);
};

SingleInputDateField.propTypes = {
  /**
     * The `input` field's `name` attribute
     */
  name: _pt.string.isRequired,

  /**
     * Called anytime any date input is blurred
     */
  onBlur: _pt.func,

  /**
     * Called anytime any date input is changed. This function is called with two arguments.
     * The first argument should be used to update whatever state your application uses to
     * supply back to this component's `value` prop in a _controlled component_ pattern.
     *
     * @param updatedValue - The input's new value
     * @param formattedValue - The input's new value with date formatting applied, included
     *   for convenience. Do not use this value as the component's `value` prop. An appropriate
     *   use for this value would be to run date-validation checks against it.
     */
  onChange: _pt.func.isRequired,

  /**
     * Sets the input's `value`. Use in combination with an `onChange` handler to implement
     * a _controlled component_ pattern. This component expects the `value` to match
     * whatever string the user types (i.e., the first argument provided to your `onChange`
     * handler).
     */
  value: _pt.string,

  /**
     * The initial month to show in the calendar picker. If not provided, defaults to the
     * month of the currently selected date.
     */

  /* -------------------------*/

  /* From DayPicker*/
  defaultMonth: _pt.instanceOf(Date),

  /**
     * Earliest day to start month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  fromDate: _pt.instanceOf(Date),

  /**
     * Earliest month to start month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  fromMonth: _pt.instanceOf(Date),

  /**
     * Earliest year to start month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  fromYear: _pt.number,

  /**
     * Latest day to end month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  toDate: _pt.instanceOf(Date),

  /**
     * Latest month to end month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  toMonth: _pt.instanceOf(Date),

  /**
     * Latest year to end month navigation in the calendar picker.
     * (This does not restrict dates entered manually.)
     */
  toYear: _pt.number
};
export default SingleInputDateField;