import { jsx as _jsx } from "react/jsx-runtime";
import { useState, useRef, useEffect } from "react";
import "./style.scss";
const OTPComponent = ({ length = 6, isDisable = false, error = false, onOTPChange, onOTPComplete, }) => {
    const [otp, setOtp] = useState("");
    const [fieldValues, setFieldValues] = useState(Array(length).fill(""));
    const inputRefs = useRef([]);
    const [inputValues, setInputValues] = useState(Array.from(Array(length)).map(() => ""));
    //here we are assigning inputValues to the input fields.
    useEffect(() => {
        inputValues.forEach((value, index) => {
            if (inputRefs.current[index]) {
                inputRefs.current[index].value = value;
            }
        });
    }, [inputValues]);
    //this function is to handle the onPaste event for an input field
    const handlePaste = (index, event) => {
        event.preventDefault();
        const pastedText = event.clipboardData?.getData("text") || "";
        // Filter to only numeric characters
        const numericOnly = pastedText.replace(/\D/g, "");
        const characters = numericOnly.split("").slice(0, length - index);
        // Update input values and field values starting from the current index
        const updatedInputValues = [...inputValues];
        const updatedFieldValues = [...fieldValues];
        characters.forEach((char, charIndex) => {
            const targetIndex = index + charIndex;
            if (targetIndex < length) {
                updatedInputValues[targetIndex] = char;
                updatedFieldValues[targetIndex] = char;
                if (inputRefs.current[targetIndex]) {
                    inputRefs.current[targetIndex].value = char;
                }
            }
        });
        // Clear remaining fields after the pasted content
        const endIndex = Math.min(index + characters.length, length);
        for (let i = endIndex; i < length; i++) {
            updatedInputValues[i] = "";
            updatedFieldValues[i] = "";
            if (inputRefs.current[i]) {
                inputRefs.current[i].value = "";
            }
        }
        setInputValues(updatedInputValues);
        setFieldValues(updatedFieldValues);
        const completeOTP = updatedFieldValues.join("");
        setOtp(completeOTP);
        // Trigger completion callback if all fields are filled
        if (updatedFieldValues.every((val) => val !== "") && onOTPComplete) {
            onOTPComplete(completeOTP);
        }
        // Focus the last filled field or next empty field
        const nextEmptyIndex = updatedFieldValues.findIndex((val) => val === "");
        const focusIndex = nextEmptyIndex === -1 ? length - 1 : Math.min(nextEmptyIndex, length - 1);
        if (inputRefs.current[focusIndex]) {
            inputRefs.current[focusIndex].focus();
        }
    };
    const handleInput = (index, event) => {
        const value = event.target.value;
        // Extract only the last character if multiple characters are entered
        const lastChar = value.slice(-1);
        if (value.length === 0) {
            // Clear the field
            event.target.value = "";
            setInputValues((prev) => {
                const updatedValues = [...prev];
                updatedValues[index] = "";
                return updatedValues;
            });
            setFieldValues((prev) => {
                const updatedValues = [...prev];
                updatedValues[index] = "";
                return updatedValues;
            });
            setOtp((prev) => prev.slice(0, index) + prev.slice(index + 1));
        }
        else if (/^\d$/.test(lastChar)) {
            // Only allow numeric input
            event.target.value = lastChar;
            const updatedInputValues = [...inputValues];
            const updatedFieldValues = [...fieldValues];
            updatedInputValues[index] = lastChar;
            updatedFieldValues[index] = lastChar;
            setInputValues(updatedInputValues);
            setFieldValues(updatedFieldValues);
            const completeOTP = updatedFieldValues.join("");
            setOtp(completeOTP);
            // Check if OTP is complete and trigger callback
            if (updatedFieldValues.every((val) => val !== "") && onOTPComplete) {
                onOTPComplete(completeOTP);
            }
            // Move to next field if not the last one
            if (index < length - 1) {
                inputRefs.current[index + 1].focus();
            }
            else {
                event.target.blur();
            }
        }
        else {
            // Invalid input - reset to previous value
            event.target.value = inputValues[index] || "";
        }
    };
    const handleBackspace = (index, event) => {
        if (event.key === "Backspace") {
            if (event.currentTarget.value === "" && index > 0) {
                // If current field is empty, move to previous and clear it
                event.preventDefault();
                const updatedInputValues = [...inputValues];
                const updatedFieldValues = [...fieldValues];
                updatedInputValues[index - 1] = "";
                updatedFieldValues[index - 1] = "";
                setInputValues(updatedInputValues);
                setFieldValues(updatedFieldValues);
                setOtp((prev) => prev.slice(0, index - 1) + prev.slice(index));
                if (inputRefs.current[index - 1]) {
                    inputRefs.current[index - 1].value = "";
                    inputRefs.current[index - 1].focus();
                }
            }
            // If current field has value, let the default behavior clear it
            // The handleInput will handle the state update
        }
    };
    const handleClick = (event) => {
        // Select all text when clicking on an input for easy clearing
        event.currentTarget.select();
    };
    const handleFocus = (event) => {
        // Select all text on focus for easy clearing
        event.currentTarget.select();
    };
    useEffect(() => {
        if (onOTPChange) {
            onOTPChange(otp);
        }
    }, [otp]);
    return (_jsx("div", { className: "otp-container", children: Array.from({ length }).map((_, index) => (_jsx("input", { autoComplete: "off", disabled: isDisable, type: "text", inputMode: "numeric", pattern: "[0-9]*", maxLength: 1, className: `otp-box ${error ? "error" : ""}`, ref: (ref) => (inputRefs.current[index] = ref), onChange: (event) => handleInput(index, event), onKeyDown: (event) => handleBackspace(index, event), onClick: handleClick, onFocus: handleFocus, onPaste: (event) => handlePaste(index, event) }, index))) }));
};
export default OTPComponent;
