"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DateTimeField = void 0;
var _InputAdornment2 = _interopRequireDefault(require("@mui/material/InputAdornment"));
var _xDatePickers = require("@mui/x-date-pickers");
var _react = require("react");
var _Field = require("../../Field.cjs");
var _i18n = require("../../i18n.generated/i18n.cjs");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/*!
 * Copyright (c) 2022-present, Okta, Inc. and/or its affiliates. All rights reserved.
 * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
 *
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and limitations under the License.
 */

const useOdysseyDateError = () => {
  const {
    t
  } = (0, _i18n.useTranslation)();
  return new Map([["invalidDate", t("picker.error.invalid")], ["maxDate", t("picker.error.maxdate")], ["minDate", t("picker.error.mindate")]]);
};
const formatDateTimeToUtcIsoDateString = value => value.toUTC().toISO();
const DateTimeField = ({
  defaultValue,
  endAdornment,
  errorMessage,
  hasInitialFocus,
  hint,
  HintLinkComponent,
  id: idOverride,
  inputRef,
  isDisabled = false,
  isOptional = false,
  isReadOnly,
  label,
  minDate,
  maxDate,
  onBlur,
  onChange,
  onFocus,
  timezone,
  value
}) => {
  const errorMap = useOdysseyDateError();
  const [displayedErrorMessage, setDisplayedErrorMessage] = (0, _react.useState)(errorMessage);
  const internalValidationError = (0, _react.useRef)();
  const localInputRef = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(inputRef, () => {
    return {
      focus: () => {
        localInputRef.current?.focus();
      }
    };
  }, []);
  const checkMinMaxValidity = (0, _react.useCallback)(value => {
    const hasMinError = minDate && value.toUTC() < minDate.toUTC();
    const hasMaxError = maxDate && value.toUTC() > maxDate.toUTC();
    if (hasMinError || hasMaxError) {
      if (hasMinError) {
        setDisplayedErrorMessage(errorMap.get("minDate"));
      }
      if (hasMaxError) {
        setDisplayedErrorMessage(errorMap.get("maxDate"));
      }
      return false;
    }
    return true;
  }, [errorMap, minDate, maxDate]);
  (0, _react.useEffect)(() => {
    if (value) {
      checkMinMaxValidity(value);
    }
    if (defaultValue) {
      checkMinMaxValidity(defaultValue);
    }
  }, [checkMinMaxValidity, defaultValue, minDate, maxDate, value]);
  const clearErrorMessages = (0, _react.useCallback)(() => {
    setDisplayedErrorMessage(undefined);
    internalValidationError.current = undefined;
  }, [internalValidationError, setDisplayedErrorMessage]);
  const validateAndCallOnChange = (0, _react.useCallback)((value, validationContext) => {
    clearErrorMessages();
    const {
      validationError
    } = validationContext;
    const hasEnteredFullYear = value?.year.toString().length === 4;
    if (validationError) {
      const odysseyValidationError = errorMap.get(validationError);
      if (odysseyValidationError) {
        internalValidationError.current = odysseyValidationError;
        if (value?.isValid && hasEnteredFullYear) {
          setDisplayedErrorMessage(odysseyValidationError);
        }
      }
    }
    if (value?.isValid && !validationError) {
      const dateStringFromDateTime = formatDateTimeToUtcIsoDateString(value);
      if (dateStringFromDateTime && checkMinMaxValidity(value)) {
        onChange?.(dateStringFromDateTime);
      }
    }
  }, [checkMinMaxValidity, clearErrorMessages, errorMap, onChange]);
  const checkFieldValidityAndSetError = (0, _react.useCallback)(event => {
    if (internalValidationError?.current && !displayedErrorMessage) {
      setDisplayedErrorMessage(internalValidationError.current);
    }
    onBlur?.(event);
  }, [displayedErrorMessage, internalValidationError, onBlur]);
  const hasVisibleAdornment = !isReadOnly && !isDisabled;
  const renderFieldComponent = (0, _react.useCallback)(({
    ariaDescribedBy,
    errorMessageElementId,
    id,
    labelElementId
  }) => (0, _jsxRuntime.jsx)(_xDatePickers.DateTimeField, {
    autoFocus: hasInitialFocus,
    defaultValue: defaultValue,
    disabled: isDisabled,
    id: id,
    inputProps: {
      "aria-describedby": ariaDescribedBy,
      "aria-errormessage": errorMessageElementId,
      "aria-labelledby": labelElementId
    },
    InputProps: {
      error: Boolean(displayedErrorMessage || errorMessage),
      endAdornment: (0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: hasVisibleAdornment && (0, _jsxRuntime.jsx)(_InputAdornment2.default, {
          position: "end",
          children: endAdornment
        })
      })
    },
    inputRef: localInputRef,
    maxDate: maxDate,
    minDate: minDate,
    name: id,
    onBlur: checkFieldValidityAndSetError,
    onChange: validateAndCallOnChange,
    onFocus: onFocus,
    readOnly: isReadOnly,
    timezone: timezone,
    value: value,
    variant: "standard"
  }), [checkFieldValidityAndSetError, defaultValue, displayedErrorMessage, endAdornment, errorMessage, hasInitialFocus, hasVisibleAdornment, isDisabled, localInputRef, minDate, maxDate, onFocus, isReadOnly, timezone, validateAndCallOnChange, value]);
  return (0, _jsxRuntime.jsx)(_Field.Field, {
    errorMessage: displayedErrorMessage || errorMessage,
    fieldType: "single",
    hasVisibleLabel: true,
    hint: hint,
    HintLinkComponent: HintLinkComponent,
    id: idOverride,
    isDisabled: isDisabled,
    isOptional: isOptional,
    label: label,
    renderFieldComponent: renderFieldComponent
  });
};
const MemoizedDateTimeField = exports.DateTimeField = (0, _react.memo)(DateTimeField);
MemoizedDateTimeField.displayName = "DateTimeField";
//# sourceMappingURL=DateTimeField.cjs.map