"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OTPInput = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeReanimated = _interopRequireDefault(require("react-native-reanimated"));
var _context = require("../../context");
var _functions = require("../../functions");
var _useErrorShakeAnimation = require("../../utils/hooks/useErrorShakeAnimation");
var _layout = require("../layout");
var _typography = require("../typography");
var _BoxedInput = require("./BoxedInput");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const OTP_ITEMS_GAP = 8;
/**
 * `OTPInput` is a component that allows the user to enter a one-time password.
 * It has an hidden `TextInput` that is used to handle the keyboard and the focus.
 * The input handles the autocompletion of the OTP code.
 * @param value - The value of the OTP code
 * @param onValueChange - The function to call when the value changes
 * @param length - The length of the OTP code
 * @param secret - If the OTP code should be hidden
 * @param autocomplete - If the OTP code should be autocompleted
 * @param onValidate - The function to call when the OTP code is validated
 * @param errorMessage - The error message to display
 * @returns
 */
const OTPInput = exports.OTPInput = /*#__PURE__*/(0, _react.forwardRef)(({
  value,
  onValueChange,
  length,
  accessibilityLabel,
  accessibilityHint,
  accessibilityValueText,
  onValidate,
  errorMessage = "",
  secret = false,
  autocomplete = false,
  inputAccessoryViewID,
  autoFocus = false,
  deleteButtonAccessibilityLabel
}, ref) => {
  const [hasFocus, setHasFocus] = (0, _react.useState)(autoFocus);
  const [hasError, setHasError] = (0, _react.useState)(false);
  const theme = (0, _context.useIOTheme)();
  const {
    translate,
    animatedStyle,
    shakeAnimation
  } = (0, _useErrorShakeAnimation.useErrorShakeAnimation)();
  const inputRef = /*#__PURE__*/(0, _react.createRef)();
  const timerRef = (0, _react.useRef)(undefined);
  const handleValidate = val => {
    if (!onValidate || val.length < length) {
      return;
    }
    const isValid = onValidate(val);
    if (!isValid) {
      setHasError(true);
      (0, _functions.triggerHaptic)("notificationError");
      // eslint-disable-next-line functional/immutable-data
      translate.value = shakeAnimation();
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
      // eslint-disable-next-line functional/immutable-data
      timerRef.current = setTimeout(() => {
        setHasError(false);
        onValueChange("");
      }, 500);
    }
  };
  (0, _react.useEffect)(() => () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
  }, []);
  const handleChange = value => {
    if (value.length > length) {
      return;
    }
    onValueChange(value);
    handleValidate(value);
  };
  const handleKeyPress = e => {
    switch (e.nativeEvent.key) {
      case "Backspace":
        if (deleteButtonAccessibilityLabel && value.length > 0) {
          _reactNative.AccessibilityInfo.announceForAccessibility(deleteButtonAccessibilityLabel);
        }
        break;
      default:
        _reactNative.AccessibilityInfo.announceForAccessibility(e.nativeEvent.key);
        break;
    }
  };
  const cells = (0, _react.useMemo)(() => Array.from({
    length
  }), [length]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNativeReanimated.default.View, {
    style: [{
      flexGrow: 1
    }, animatedStyle],
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Pressable, {
      onPress: () => {
        inputRef.current?.focus();
        setHasFocus(true);
      },
      ref: ref,
      accessible: false,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.TextInput, {
        value: value,
        onChangeText: handleChange,
        onKeyPress: handleKeyPress,
        caretHidden: _reactNative.Platform.OS === "ios",
        style: [_reactNative.StyleSheet.absoluteFillObject, _reactNative.Platform.select({
          ios: {
            opacity: 0.01
          },
          android: {
            opacity: 0
          }
        })],
        maxLength: length,
        ref: inputRef,
        onBlur: () => setHasFocus(false),
        keyboardType: "numeric",
        inputMode: "numeric",
        returnKeyType: "done",
        textContentType: "oneTimeCode",
        autoComplete: autocomplete ? "sms-otp" : undefined,
        inputAccessoryViewID: inputAccessoryViewID,
        accessible: true,
        accessibilityLabel: accessibilityLabel,
        accessibilityHint: accessibilityHint
        // Ensure the screen reader pronounces the code digit by digit
        ,
        accessibilityValue: {
          text: accessibilityValueText?.({
            valueLength: value.length,
            length
          }) ?? value.split("").join(" ")
        },
        autoFocus: autoFocus,
        secureTextEntry: secret
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: {
          flexDirection: "row",
          justifyContent: "space-between",
          columnGap: OTP_ITEMS_GAP,
          flexGrow: 1,
          zIndex: 10
        },
        accessibilityElementsHidden: true,
        importantForAccessibility: "no-hide-descendants",
        children: cells.map((_, i) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_BoxedInput.BoxedInput, {
          status: hasError ? "error" : hasFocus && value.length === i ? "focus" : "default",
          secret: secret,
          value: value[i]
        }, i))
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_layout.VSpacer, {
      size: 4
    }), hasError && errorMessage && /*#__PURE__*/(0, _jsxRuntime.jsx)(_typography.BodySmall, {
      weight: "Semibold",
      color: theme.errorText,
      style: {
        textAlign: "center"
      },
      children: errorMessage
    })]
  });
});
//# sourceMappingURL=OTPInput.js.map