import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { forwardRef, useEffect, useId, useMemo, useRef, useState } from "react";
import { cva } from "class-variance-authority";
import { cn } from "../utils/css";
import { InputMask } from "./inputMask";
import { Tooltip } from "../tooltip";
import { CircleCloseIcon } from "../icon";
import { findLongestCommonSubString } from "../utils/string";
import { parseInputHelper } from "./utils";
const inputVariants = cva([
    "orderly-rounded"
], {
    variants: {
        variant: {
            outlined: "orderly-border orderly-border-slate-300",
            filled: "orderly-bg-base-700 orderly-border orderly-border-transparent"
        },
        size: {
            small: "orderly-h-[28px]",
            default: "orderly-h-[40px]"
        },
        fullWidth: {
            true: "orderly-w-full"
        },
        disabled: {
            true: "orderly-opacity-70 orderly-cursor-not-allowed"
        },
        error: {
            true: "orderly-border orderly-border-danger"
        }
    },
    // compoundVariants: [
    //   {
    //     variant: "filled",
    //     error: true,
    //     class: "border border-danger",
    //   },
    //   {
    //     variant: "outlined",
    //   }
    // ],
    defaultVariants: {
        size: "default",
        variant: "filled"
    }
});
export const Input = /*#__PURE__*/ forwardRef(({ className, containerClassName, size, variant, fullWidth, disabled, prefix, suffix, error, onClean, helpText, loading, onChange, onValueChange, thousandSeparator, fixClassName, id, ...props }, ref)=>{
    const [showTooltip, setShowTooltip] = useState(false);
    const [cursor, setCursor] = useState(null);
    const innerInputRef = useRef(null);
    const prevInputValue = useRef(null);
    const cid = useId();
    useEffect(()=>{
        if (!ref) return;
        if (typeof ref === "function") {
            ref(innerInputRef.current);
        } else {
            ref.current = innerInputRef.current;
        }
    }, [
        innerInputRef,
        ref
    ]);
    useEffect(()=>{
        if (typeof error === "undefined") {
            return;
        }
        setShowTooltip(!!error);
    }, [
        error
    ]);
    // fix cursor pointer jump to end;
    useEffect(()=>{
        if (document.activeElement !== innerInputRef.current) return;
        // filter the thousands separator
        const nextValueLen = `${props.value}`.length;
        const prevValueLen = prevInputValue.current?.length || 0;
        const next = cursor ? cursor + (nextValueLen - prevValueLen) : 0;
        innerInputRef.current?.setSelectionRange(next, next);
    }, [
        props.value
    ]);
    const onInputChange = (event)=>{
        if (event.target.value.length < props.value?.length) {
            const currentCursor = event.target.selectionStart;
            const diffIndex = findLongestCommonSubString(`${props.value}`, event.target.value);
            if (diffIndex > -1) {
                const diffStr = `${props.value}`.at(diffIndex);
                if (diffStr === ",") {
                    event.target.value = `${event.target.value.substring(0, diffIndex - 1)}${event.target.value.substring(diffIndex)}`;
                    event.target.selectionStart = currentCursor ? currentCursor - 1 : 0;
                }
            }
        }
        if (typeof onChange === "function") {
            onChange(event);
        }
        if (typeof onValueChange === "function") {
            let value = event.target.value;
            if (thousandSeparator) {
                value = parseInputHelper(value);
            }
            onValueChange(value);
        }
        prevInputValue.current = event.target.value;
        setCursor(event.target.selectionStart);
    };
    const cleanButton = useMemo(()=>{
        if (typeof onClean === "undefined") {
            return null;
        }
        return /*#__PURE__*/ _jsx("button", {
            className: "orderly-hidden peer-focus:orderly-flex orderly-px-3 orderly-items-center orderly-justify-center",
            onMouseDown: (event)=>{
                event.preventDefault();
                event.stopPropagation();
                onClean?.();
            },
            children: /*#__PURE__*/ _jsx("span", {
                className: "orderly-inline-flex orderly-rounded-full orderly-w-[20px] orderly-h-[20px] orderly-items-center orderly-justify-center",
                children: /*#__PURE__*/ _jsx(CircleCloseIcon, {
                    size: 16
                })
            })
        });
    }, [
        onClean
    ]);
    const onInputFocus = (event)=>{
        setShowTooltip(!!error);
    };
    const onInputBlur = (event)=>{
        setShowTooltip(false);
    };
    const prefixElement = useMemo(()=>{
        if (typeof prefix === "undefined") {
            return null;
        }
        if (typeof prefix === "string") {
            return /*#__PURE__*/ _jsx(InputMask, {
                name: id || cid,
                className: cn("orderly-text-3xs orderly-select-none orderly-text-base-contrast-54 orderly-font-semibold desktop:orderly-text-xs", fixClassName),
                children: prefix
            });
        }
        return prefix;
    }, [
        prefix,
        fixClassName
    ]);
    const suffixElement = useMemo(()=>{
        if (typeof suffix === "undefined") {
            return null;
        }
        if (typeof suffix === "string") {
            return /*#__PURE__*/ _jsx(InputMask, {
                name: id || cid,
                className: cn("orderly-text-3xs orderly-select-none orderly-text-base-contrast-54 orderly-font-semibold desktop:orderly-text-xs", fixClassName),
                children: suffix
            });
        }
        return suffix;
    }, [
        suffix,
        fixClassName
    ]);
    return /*#__PURE__*/ _jsx(Tooltip, {
        className: cn("orderly-text-base-contrast orderly-text-4xs", props.tooltipClassName),
        open: showTooltip,
        content: helpText ?? "input help text",
        sideOffset: 5,
        children: /*#__PURE__*/ _jsxs("div", {
            className: cn("orderly-input-container", props.readOnly && "orderly-input-container-readonly", "orderly-flex orderly-flex-row orderly-items-center orderly-rounded focus-within:orderly-outline focus-within:orderly-outline-1 orderly-outline-primary", inputVariants({
                size,
                fullWidth,
                disabled,
                variant,
                error
            }), (props.readOnly || !!error) && "focus-within:orderly-outline-none", containerClassName),
            children: [
                prefixElement,
                /*#__PURE__*/ _jsx("input", {
                    ref: innerInputRef,
                    type: "text",
                    onFocus: onInputFocus,
                    onBlur: onInputBlur,
                    onChange: onInputChange,
                    ...props,
                    id: id || cid,
                    disabled: disabled,
                    className: cn("orderly-input", "orderly-bg-transparent orderly-px-3 orderly-flex-1 focus-visible:orderly-outline-none orderly-h-full orderly-w-full orderly-peer placeholder:orderly-text-base-contrast-20 placeholder:orderly-text-xs orderly-tabular-nums", typeof prefix !== "undefined" && "orderly-px-0", className)
                }),
                cleanButton,
                suffixElement
            ]
        })
    });
});

//# sourceMappingURL=index.js.map