import React from 'react';
import { HStack } from '../../primitives';
import { usePropsConfig } from '../../../theme';
import { FormControlContext } from '../FormControl';
import { Platform } from 'react-native';
export const PinInputContext = /*#__PURE__*/React.createContext({});

const PinInput = ({
  children,
  ...props
}) => {
  const {
    manageFocus,
    defaultValue,
    value,
    space,
    ...newProps
  } = usePropsConfig('PinInput', props);
  const formControlContext = React.useContext(FormControlContext);
  const RefList = [];

  const setRefList = (ref, index) => {
    RefList[index] = ref;
  };

  const [pinInputValue, setPinInputValue] = React.useState(value || defaultValue);

  const handleChange = (newValue, fieldIndex) => {
    let temp = pinInputValue && [...pinInputValue] || [];
    temp[fieldIndex] = newValue;
    setPinInputValue(temp.join(''));
    if (newValue && manageFocus && fieldIndex + 1 < RefList.length) RefList[fieldIndex + 1].current.focus();
    if (!newValue && manageFocus && fieldIndex - 1 > -1) RefList[fieldIndex - 1].current.focus();
    return temp.join('');
  };

  const handleMultiValueChange = (newValue, fieldIndex) => {
    const pinFieldLength = RefList.length;
    const newValueLength = newValue.length;

    if (newValueLength >= pinFieldLength && newValueLength > 2) {
      let splicedValue = newValue ? [...newValue] : [];
      splicedValue.splice(pinFieldLength);
      RefList[pinFieldLength - 1].current.focus();
      setPinInputValue(splicedValue.join(''));
    }

    if (Platform.OS === 'android' && newValue) {
      const temp = pinInputValue ? [...pinInputValue] : [];
      temp[fieldIndex] = JSON.stringify(parseInt(newValue, 10) % 10);
      if (newValue && manageFocus && fieldIndex + 1 < RefList.length) RefList[fieldIndex + 1].current.focus(); // Backward focus is handled by handle change function.

      setPinInputValue(temp.join(''));
    }
  };

  const indexSetter = allChildren => {
    let pinInputFiledCounter = -1;
    return React.Children.map(allChildren, child => {
      if (child.type.name !== 'PinInputFiled') return child;else {
        pinInputFiledCounter++;
        return /*#__PURE__*/React.cloneElement(child, {
          fieldIndex: pinInputFiledCounter
        }, child.props.children);
      }
    });
  };

  return /*#__PURE__*/React.createElement(PinInputContext.Provider, {
    value: { ...formControlContext,
      ...newProps,
      setRefList,
      handleChange,
      handleMultiValueChange,
      value: pinInputValue
    }
  }, children && /*#__PURE__*/React.createElement(HStack, {
    flexDirection: "row",
    space: space
  }, indexSetter(children)));
};

export default PinInput;
export { default as PinInputField } from './PinInputField';
//# sourceMappingURL=index.js.map