"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _compat = require("preact/compat");
var _CustomDayPicker = _interopRequireDefault(require("./CustomDayPicker"));
var _classnames = _interopRequireDefault(require("classnames"));
var _cleanFieldProps = _interopRequireDefault(require("../utilities/cleanFieldProps"));
var _describeField = _interopRequireDefault(require("../utilities/describeField"));
var _dateFns = require("date-fns");
var _mergeIds = _interopRequireDefault(require("../utilities/mergeIds"));
var _useLabelMask = _interopRequireWildcard(require("../TextField/useLabelMask"));
var _useClickOutsideHandler = _interopRequireDefault(require("../utilities/useClickOutsideHandler"));
var _usePressEscapeHandler = _interopRequireDefault(require("../utilities/usePressEscapeHandler"));
var _useId = _interopRequireDefault(require("../utilities/useId"));
var _CalendarIcon = require("../Icons/CalendarIcon");
var _Label = require("../Label");
var _TextField = require("../TextField");
var _i18n = require("../i18n");
var _useLabelProps = require("../Label/useLabelProps");
var _useHint = require("../Hint/useHint");
var _useInlineError = require("../InlineError/useInlineError");
var _jsxRuntime = require("preact/compat/jsx-runtime");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
 * For information about how and when to use this component, refer to the
 * [Single Input Date Field](https://design.cms.gov/components/date-field/single-input-date-field/) and
 * [Calendar Picker](https://design.cms.gov/components/date-field/date-picker/) documentation pages.
 */
const SingleInputDateField = props => {
  const {
    className,
    onChange,
    defaultMonth,
    fromDate,
    fromMonth,
    fromYear,
    toDate,
    toMonth,
    toYear,
    ...remainingProps
  } = props;
  const withPicker = (fromDate != null || fromMonth != null || Number.isInteger(fromYear)) && (toDate != null || toMonth != null || Number.isInteger(toYear));
  const [pickerVisible, setPickerVisible] = (0, _compat.useState)(false);
  const id = (0, _useId.default)('date-field--', props.id);
  const isControlled = remainingProps.value !== undefined;
  const [internalValueState, setInternalValueState] = (0, _compat.useState)(remainingProps.defaultValue);
  const value = isControlled ? remainingProps.value : internalValueState;

  // Set up change handlers
  const handleInputChange = event => {
    const updatedValue = event.currentTarget.value;
    if (onChange) {
      onChange(updatedValue, (0, _useLabelMask.DATE_MASK)(updatedValue, true));
    }
    if (!isControlled) {
      setInternalValueState(updatedValue);
    }
  };
  const handlePickerChange = date => {
    const updatedValue = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
    const maskedValue = (0, _useLabelMask.DATE_MASK)(updatedValue);
    if (onChange) {
      onChange(maskedValue, (0, _useLabelMask.DATE_MASK)(updatedValue, true));
    }
    if (!isControlled) {
      setInternalValueState(maskedValue);
    }
    setPickerVisible(false);
    inputRef.current?.focus();
  };

  // Collect all the props and elements for the input and its labels
  const {
    errorId,
    topError,
    bottomError,
    invalid
  } = (0, _useInlineError.useInlineError)({
    ...props,
    id
  });
  const {
    hintId,
    hintElement
  } = (0, _useHint.useHint)({
    ...props,
    id
  });
  const labelProps = (0, _useLabelProps.useLabelProps)({
    ...props,
    id
  });
  const inputRef = (0, _compat.useRef)();
  const {
    labelMask,
    inputProps
  } = (0, _useLabelMask.default)(_useLabelMask.DATE_MASK, {
    ...(0, _cleanFieldProps.default)(remainingProps),
    value,
    id,
    onChange: handleInputChange,
    type: 'text',
    inputRef,
    'aria-invalid': invalid,
    'aria-describedby': (0, _describeField.default)({
      ...props,
      errorId,
      hintId
    })
  });

  // Handle alternate ways of closing the day picker
  const dayPickerRef = (0, _compat.useRef)();
  const calendarButtonRef = (0, _compat.useRef)();
  (0, _useClickOutsideHandler.default)([dayPickerRef, calendarButtonRef], () => setPickerVisible(false));
  (0, _usePressEscapeHandler.default)(dayPickerRef, () => {
    setPickerVisible(false);
    inputRef.current?.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`
  const dateString = (0, _useLabelMask.DATE_MASK)(props.value, true);
  const validDateString = (0, _dateFns.isMatch)(dateString, 'MM/dd/yyyy');
  const date = validDateString ? new Date(dateString) : null;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: (0, _classnames.default)('ds-c-single-input-date-field', withPicker && 'ds-c-single-input-date-field--with-picker', className),
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Label.Label, {
      ...labelProps,
      fieldId: id
    }), hintElement, topError, labelMask, /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "ds-c-single-input-date-field__field-wrapper",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_TextField.TextInput, {
        ...inputProps
      }), withPicker && /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
        className: "ds-c-single-input-date-field__button",
        onClick: () => setPickerVisible(!pickerVisible),
        type: "button",
        ref: calendarButtonRef,
        "aria-describedby": (0, _mergeIds.default)(labelProps.id, hintId),
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_CalendarIcon.CalendarIcon, {
          ariaHidden: false,
          title: (0, _i18n.t)(pickerVisible ? 'singleInputDateField.close' : 'singleInputDateField.open'),
          id: `${id}__icon`
        })
      })]
    }), pickerVisible && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      ref: dayPickerRef,
      role: "dialog",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_CustomDayPicker.default, {
        selected: date,
        onSelect: handlePickerChange,
        defaultMonth: date ?? defaultMonth,
        fromDate,
        fromMonth,
        fromYear,
        toDate,
        toMonth,
        toYear
      })
    }), bottomError]
  });
};
var _default = exports.default = SingleInputDateField;