import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2025 GoodData Corporation
import { useCallback, useEffect, useState } from "react";
import cx from "classnames";
import { isEmpty } from "lodash-es";
import { FormattedMessage } from "react-intl";
import { v4 } from "uuid";
import { Bubble } from "../../../../Bubble/Bubble.js";
const VALID_INPUT = "^[0-9]+[.,]?[0-9]*$";
const bubbleAlignPoints = [{ align: "bl tl" }];
const bubbleArrowOffsets = { "bl tl": [0, 10] };
const validHeight = (height) => {
    return !(parseFloat(height) === 0 || height.endsWith("."));
};
/**
 * @internal
 */
export function NumericInput({ value, onValueChanged }) {
    const [validPressedButton, setValidPressedButton] = useState(true);
    const [anchorId] = useState(`numeric-input-id-${v4()}`);
    useEffect(() => {
        if (!validPressedButton) {
            setTimeout(() => setValidPressedButton(true), 2000);
        }
    }, [validPressedButton]);
    const handleHeightInputChange = useCallback((e) => {
        const val = e.target.value.replace(/,/, ".");
        if (val.match(VALID_INPUT)) {
            onValueChanged(val);
        }
        else if (isEmpty(val)) {
            onValueChanged("");
        }
    }, [onValueChanged]);
    const correctKeyPressed = useCallback((e) => {
        const value = e.target.value.replace(/,/, ".");
        setValidPressedButton((value.match(VALID_INPUT) || isEmpty(value)) && value.split(".").length <= 2);
    }, []);
    const onChanged = useCallback((e) => {
        correctKeyPressed(e);
        handleHeightInputChange(e);
    }, [handleHeightInputChange, correctKeyPressed]);
    return (_jsxs("label", { className: "gd-input", children: [
            _jsx("div", { className: cx("gd-input-wrapper", anchorId), children: _jsx("input", { className: cx("gd-input-field s-embed-dialog-custom-height", {
                        "gd-embed-input-numeric-invalid": !validHeight(value),
                    }), type: "text", value: value, onChange: onChanged }) }), !validHeight(value) && (_jsx(Bubble, { alignTo: `.${anchorId}`, alignPoints: bubbleAlignPoints, arrowOffsets: bubbleArrowOffsets, className: "bubble-negative", children: _jsx(FormattedMessage, { id: "embed.dialog.numeric.input.validation" }) })), !validPressedButton && (_jsx(Bubble, { alignTo: `.${anchorId}`, alignPoints: bubbleAlignPoints, arrowOffsets: bubbleArrowOffsets, className: "bubble-warning", children: _jsx(FormattedMessage, { id: "embed.dialog.numeric.input.warning" }) }))] }));
}
