import React, { forwardRef, useEffect, useRef, useState } from "react";
import { cx, isNumber } from "../../../../utils";
import { useDidMountEffect, useForkRef } from "../../../../hooks";
import { keyCodes } from "../../../../utils/constants";
import { defaultCharacterWidth, excludingNumberSchema, getPreciseValue, numberSchema } from "../../utils";
import { classes } from "../../NumberInput.tokens";
import { AdditionalText, Input, InputWrapper, DynamicInput, InputWidthHelper, TextWrapper, StyledSpinner, Loader } from "./Input.styles";
export const NumberInput = /*#__PURE__*/ forwardRef(({ value, precision, min, max, isLoading, loader, disabled, segmentation, textBefore, textAfter, isManualInput, isInputFocused, setIsInputFocused, setIsAnimationRun, setInnerValue, onChange, onBlur, onKeyDown, onDecrementKey, onIncrementKey, shouldFocusInput, onFocusHandled, ...rest }, ref)=>{
    const [dynamicWidth, setDynamicWidth] = useState(value ? `${String(value).length}ch` : defaultCharacterWidth);
    const [lastValidValue, setLastValidValue] = useState(value);
    const [errorClass, setErrorClass] = useState(undefined);
    const [errorValue, setErrorValue] = useState();
    const inputHelperRef = useRef(null);
    const wrapperRef = useRef(null);
    const textWrapperRef = useRef(null);
    const inputRef = useRef(null);
    const inputForkRef = useForkRef(inputRef, ref);
    const solidViewClass = segmentation === 'solid' ? classes.solidView : undefined;
    const manualInputClass = isManualInput ? classes.manualInput : undefined;
    const getInputWidth = (firstRender = true)=>{
        if (!firstRender && inputHelperRef.current?.clientWidth) {
            return `${inputHelperRef.current?.clientWidth}px`;
        }
        if (value) {
            return `${String(value).length}ch`;
        }
        return defaultCharacterWidth;
    };
    const setValues = (event, newValue)=>{
        setLastValidValue(newValue);
        setInnerValue(newValue);
        if (onChange) {
            onChange(event, newValue);
        }
    };
    const validateValue = (newValue)=>{
        if (!newValue?.toString() || !isNumber(newValue)) {
            setValues(null, '');
            setIsAnimationRun(false);
            return;
        }
        const resValue = Number(newValue);
        if (max !== undefined && resValue > max) {
            setErrorClass(classes.errorAnimation);
            setErrorValue(max);
            setIsAnimationRun(true);
            return;
        }
        if (min !== undefined && resValue < min) {
            setErrorClass(classes.errorAnimation);
            setErrorValue(min);
            setIsAnimationRun(true);
            return;
        }
        if (String(newValue).endsWith('.')) {
            setValues(null, Number(newValue));
            setIsAnimationRun(false);
            return;
        }
        if (precision !== undefined) {
            const preciseNewValue = Number(getPreciseValue(newValue, precision));
            setValues(null, preciseNewValue);
        }
        setIsAnimationRun(false);
    };
    const handleManualInputChange = (event)=>{
        if (!isManualInput || disabled) {
            return;
        }
        setIsAnimationRun(true);
        const { value: newValue } = event.target;
        if (!isNumber(lastValidValue) && lastValidValue !== '' && !newValue) {
            return;
        }
        if (!newValue) {
            setInnerValue('');
            if (onChange) {
                onChange(event, '');
            }
            return;
        }
        const cleanValue = newValue.replace(excludingNumberSchema, '');
        if (cleanValue.endsWith('.') || cleanValue === '-') {
            setInnerValue(cleanValue);
            if (onChange) {
                onChange(event, cleanValue);
            }
            return;
        }
        const isValid = numberSchema.test(cleanValue);
        if (!isValid) {
            setValues(event, lastValidValue);
            return;
        }
        if (textWrapperRef?.current && wrapperRef?.current && textWrapperRef?.current?.clientWidth > wrapperRef?.current?.clientWidth) {
            wrapperRef.current.scrollLeft = textWrapperRef.current.offsetWidth - textWrapperRef.current.offsetLeft || 0;
        }
        setValues(event, cleanValue);
    };
    const handleClickInputWrapper = ()=>{
        if (!isManualInput || !inputRef.current) {
            return;
        }
        if (!isInputFocused) {
            inputRef.current.focus();
        }
        setIsInputFocused(true);
    };
    const handleBlur = (event)=>{
        validateValue(value);
        setIsInputFocused(false);
        if (onBlur) {
            onBlur(event);
        }
    };
    const handleFocus = ()=>{
        if (isManualInput && !isInputFocused) {
            inputRef.current?.select();
        }
        setIsInputFocused(true);
    };
    const handleKeyDown = (event)=>{
        if (disabled) {
            return;
        }
        if (event.keyCode === keyCodes.Up && onIncrementKey) {
            event.preventDefault();
            onIncrementKey();
            return;
        }
        if (event.keyCode === keyCodes.Down && onDecrementKey) {
            event.preventDefault();
            onDecrementKey();
            return;
        }
        if (event.keyCode === keyCodes.Enter) {
            event.preventDefault();
            validateValue(value);
            if (onKeyDown) {
                onKeyDown(event);
            }
        }
    };
    const handleEndErrorAnimation = (correctValue)=>{
        setIsAnimationRun(false);
        setIsInputFocused(false);
        setErrorClass(undefined);
        setValues(null, correctValue);
    };
    useEffect(()=>{
        setDynamicWidth(getInputWidth());
    }, []);
    useDidMountEffect(()=>{
        setDynamicWidth(getInputWidth(false));
    }, [
        value
    ]);
    useEffect(()=>{
        if (shouldFocusInput && inputRef.current) {
            inputRef.current.focus();
            onFocusHandled?.();
        }
    }, [
        shouldFocusInput
    ]);
    return /*#__PURE__*/ React.createElement(InputWrapper, {
        ref: wrapperRef,
        className: cx(solidViewClass, errorClass, manualInputClass),
        isManualInput: Boolean(isManualInput),
        onClick: handleClickInputWrapper
    }, /*#__PURE__*/ React.createElement(TextWrapper, {
        ref: textWrapperRef
    }, !isLoading && textBefore && /*#__PURE__*/ React.createElement(AdditionalText, {
        className: classes.textBefore
    }, textBefore), isLoading ? /*#__PURE__*/ React.createElement(Loader, null, loader || /*#__PURE__*/ React.createElement(StyledSpinner, null)) : /*#__PURE__*/ React.createElement(DynamicInput, null, /*#__PURE__*/ React.createElement(Input, {
        ref: inputForkRef,
        dynamicWidth: dynamicWidth,
        value: value,
        isManualInput: Boolean(isManualInput),
        tabIndex: disabled ? -1 : 0,
        onChange: handleManualInputChange,
        onFocus: handleFocus,
        onBlur: handleBlur,
        onKeyDown: handleKeyDown,
        onAnimationEnd: ()=>handleEndErrorAnimation(Number(errorValue)),
        ...rest
    }), /*#__PURE__*/ React.createElement(InputWidthHelper, {
        ref: inputHelperRef
    }, value)), !isLoading && textAfter && /*#__PURE__*/ React.createElement(AdditionalText, {
        className: classes.textAfter
    }, textAfter)));
});
