"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const lodash_1 = require("lodash");
const react_native_1 = require("react-native");
const enums_1 = require("../../enums");
const hooks_1 = require("../../utils/hooks");
const FormError_1 = tslib_1.__importDefault(require("../FormError"));
const MaskedTextInput_1 = tslib_1.__importDefault(require("./MaskedTextInput"));
const styles_1 = require("./styles");
const TextInput = ({ id, accessibility, accessibilityLabel, testID, large = false, contrast = false, centered = false, withBottomline = true, multiline = false, autoFocus = false, allowFontScaling = false, keyboardType = 'default', iconSize, iconTouchableEnabled = false, status = enums_1.InputStatus.Default, maskType = null, iconNameBordered = '', iconName, label = '', value = '', placeholder = '', error = '', style = {}, errorStyle = {}, textStyle = {}, rootStyle = {}, labelStyle = {}, iconHitSlop = {}, inputRef, onBlur = () => { }, onFocus = () => { }, onChangeText = () => { }, onPressIcon = () => { }, onRightIconPress = () => { }, inputLeftPadding, inputRightPadding, rightIconName, leftIconName, leftIconColor, iconColor, inputPadding, borderedBackgroundColor, borderedHeight, borderedColor, focusBorderedColor, borderedWidth = 1, borderedRadius = 0, iconType = enums_1.IconFonts.FontAwesome, fixedLabelVariant = 'xs', suppressAnimation = true, borderedLabel = '', showBorderErrored = true, showIconErrored = true, iconSets, hidePlaceholderOnFocus = false, isFloating, animationValues = {
    upper: styles_1.LABEL_UPPER_STYLE,
    lower: styles_1.LABEL_LOWER_STYLE,
}, ...rest
// eslint-disable-next-line sonarjs/cognitive-complexity
 }) => {
    const customRef = (0, hooks_1.useAutoFocus)(autoFocus, inputRef);
    const animationInitialValues = {
        top: suppressAnimation
            ? animationValues.upper.top
            : animationValues.lower.top,
        fontSize: suppressAnimation
            ? animationValues.upper.fontSize
            : animationValues.lower.fontSize,
        opacity: suppressAnimation
            ? animationValues.upper.opacity
            : animationValues.lower.opacity,
    };
    const [labelAnimatedStyle] = (0, react_1.useState)({
        top: new react_native_1.Animated.Value(animationInitialValues.top),
        fontSize: new react_native_1.Animated.Value(animationInitialValues.fontSize),
        opacity: new react_native_1.Animated.Value(animationInitialValues.opacity),
    });
    const [labelAnimatedFinish, setLabelAnimatedFinish] = (0, react_1.useState)({
        fontWeight: styles_1.FONT_WEIGHT_LOWER,
    });
    const [isPlaceholder, setIsPlaceHolder] = (0, react_1.useState)(suppressAnimation ? false : true);
    const [focusBorderColor, setFocusBorderColor] = (0, react_1.useState)(borderedColor);
    const previousValue = (0, hooks_1.usePrevious)(value || '');
    const labelVariant = large ? 'md' : 'xs';
    const textVariant = large ? 'lg' : 'md';
    const placeholderVariant = large ? 'lg' : 'md';
    const animateComponent = (0, react_1.useCallback)((updatedLabelStyle) => {
        const animations = Object.keys(updatedLabelStyle).map((animationProp) => react_native_1.Animated.timing(labelAnimatedStyle[animationProp], {
            toValue: updatedLabelStyle[animationProp],
            duration: 200,
            useNativeDriver: false,
        }));
        react_native_1.Animated.parallel(animations).start();
    }, [labelAnimatedStyle]);
    const animationUp = () => {
        animateComponent(animationValues.upper);
        setLabelAnimatedFinish({ fontWeight: styles_1.FONT_WEIGHT_UPPER });
    };
    const animationDown = () => {
        animateComponent(animationValues.lower);
        setLabelAnimatedFinish({ fontWeight: styles_1.FONT_WEIGHT_LOWER });
    };
    const handleOnFocus = (event) => {
        if (isPlaceholder && !suppressAnimation && !hidePlaceholderOnFocus) {
            animationUp();
        }
        if (borderedHeight) {
            setFocusBorderColor(focusBorderedColor);
        }
        setIsPlaceHolder(false);
        onFocus(event);
    };
    const handleOnBlur = (event) => {
        if ((0, lodash_1.isEmpty)(value) &&
            !(0, lodash_1.isEmpty)(label) &&
            !suppressAnimation &&
            !hidePlaceholderOnFocus) {
            setIsPlaceHolder(true);
            animationDown();
        }
        if ((0, lodash_1.isEmpty)(label)) {
            setIsPlaceHolder(false);
        }
        if (borderedHeight) {
            setFocusBorderColor(borderedColor);
        }
        onBlur(event);
    };
    const renderTextInput = (inputStatus) => {
        const renderPlaceholder = (0, lodash_1.isEmpty)(value) && !isPlaceholder ? placeholder : '';
        const textInputProps = {
            inputRef: customRef,
            id,
            accessibility,
            accessibilityLabel,
            testID,
            large,
            variant: textVariant,
            centered,
            contrast,
            withBottomline,
            multiline,
            value,
            keyboardType,
            onChangeText,
            allowFontScaling,
            isPlaceholder,
            status: inputStatus,
            placeholder: renderPlaceholder,
            style: textStyle,
            onBlur: handleOnBlur,
            onFocus: handleOnFocus,
            underlineColorAndroid: 'transparent',
            autoFocus,
            ...rest,
        };
        return (<MaskedTextInput_1.default {...textInputProps} maskType={maskType || 'no-mask'} accessibilityLabel={accessibilityLabel || accessibility} testID={testID || id || accessibility}/>);
    };
    const setAnimation = () => {
        const wasEmpty = previousValue?.length === 0;
        if (value?.length &&
            wasEmpty &&
            !suppressAnimation &&
            !hidePlaceholderOnFocus) {
            animationUp();
        }
        if ((0, lodash_1.isEmpty)(label) || (value?.length && hidePlaceholderOnFocus)) {
            setIsPlaceHolder(false);
        }
    };
    (0, react_1.useEffect)(() => {
        setAnimation();
    }, [value, previousValue]);
    const hasError = !(0, lodash_1.isEmpty)(error);
    const icon = iconName;
    const iconBordered = iconNameBordered;
    const renderStatus = hasError ? enums_1.InputStatus.Danger : status;
    const renderIcon = (iconProp, isLeft) => (<styles_1.Icon testID={`icon_${iconProp || ''}`} type={iconType} id={`id_${iconProp}`} accessibility={`icon_${accessibility}`} size={iconSize} name={iconProp || ''} contrast={contrast} error={hasError} touchable={iconTouchableEnabled} onPress={!!rightIconName ? onRightIconPress : onPressIcon} hitSlop={iconHitSlop} iconColor={isLeft ? leftIconColor : iconColor} showIconErrored={showIconErrored} iconSets={iconSets}/>);
    return (<styles_1.RootWrapper style={rootStyle}>
      <FormError_1.default id={id || accessibility} accessibility={accessibility} centered={centered} error={error} large={large} style={errorStyle}>
        <styles_1.InputWrapper style={style} multiline={multiline}>
          <styles_1.BorderedWrapper borderedBackgroundColor={borderedBackgroundColor} borderedHeight={borderedHeight} borderedColor={focusBorderColor} borderedRadius={borderedRadius} borderedWidth={borderedWidth} error={hasError} showBorderErrored={showBorderErrored} isFloating={isFloating}>
            {!centered &&
            !borderedHeight &&
            !(hidePlaceholderOnFocus && !isPlaceholder) && (<styles_1.Label status={status} contrast={contrast} style={[labelAnimatedStyle, labelStyle]} variant={isPlaceholder ? placeholderVariant : labelVariant} testID={`error_${id || accessibility}`} accessibilityLabel={`Erro ${accessibility}`}>
                  {label}
                </styles_1.Label>)}
            {!(0, lodash_1.isEmpty)(borderedLabel) && (0, lodash_1.isEmpty)(label) && !!borderedHeight && (<styles_1.FixedLabelAboveBorder style={labelStyle} variant={fixedLabelVariant}>
                {borderedLabel}
              </styles_1.FixedLabelAboveBorder>)}
            {borderedHeight ? (<styles_1.InputBorderedAreaWrapper hasBottomLine={withBottomline}>
                {!!leftIconName && renderIcon(leftIconName, true)}
                {!(0, lodash_1.isEmpty)(iconBordered) && renderIcon(iconBordered, true)}
                <styles_1.InputBorderedColumnWrapper hasLeftIcon={!(0, lodash_1.isEmpty)(iconBordered)} multiline={multiline} padding={inputPadding} isFloating={isFloating}>
                  {!(0, lodash_1.isEmpty)(label) && (0, lodash_1.isEmpty)(borderedLabel) && (<styles_1.FixedLabel hasLeftIcon={!(0, lodash_1.isEmpty)(iconBordered)} style={fixedLabelVariant === 'animated'
                    ? [
                        labelAnimatedStyle,
                        labelAnimatedFinish,
                        labelStyle,
                    ]
                    : labelStyle} variant={fixedLabelVariant}>
                      {label}
                    </styles_1.FixedLabel>)}
                  {renderTextInput(renderStatus)}
                </styles_1.InputBorderedColumnWrapper>
                {!!rightIconName && renderIcon(rightIconName)}
                {!(0, lodash_1.isEmpty)(icon) && renderIcon(icon || '')}
              </styles_1.InputBorderedAreaWrapper>) : (<styles_1.InputAreaWrapper multiline={multiline} padding={inputPadding} rightIcon={!!rightIconName} inputLeftPadding={inputLeftPadding} inputRightPadding={inputRightPadding}>
                {borderedHeight && <styles_1.FixedLabel>{label}</styles_1.FixedLabel>}
                {!!leftIconName && renderIcon(leftIconName, true)}
                {renderTextInput(renderStatus)}
                {!!rightIconName && renderIcon(rightIconName)}
                {!leftIconName &&
                !rightIconName &&
                !(0, lodash_1.isEmpty)(icon) &&
                renderIcon(icon)}
              </styles_1.InputAreaWrapper>)}
            {withBottomline && (<styles_1.BottomLine status={status} contrast={contrast}/>)}
          </styles_1.BorderedWrapper>
        </styles_1.InputWrapper>
      </FormError_1.default>
    </styles_1.RootWrapper>);
};
exports.default = TextInput;
//# sourceMappingURL=index.js.map