import React from "react";
import { generateOutputNode } from "../../utils/output.utils";
const PasswordInput = ({ prefix, prompt, inputRef, cursorClassName, isFocused, focusInput, blurInput, handleEnter, handleError, options, displayOutput, }) => {
    const [input, setInput] = React.useState("");
    const [cursorPosition, setCursorPosition] = React.useState(0);
    const [numTries, setNumTries] = React.useState(1);
    const [hideCursor, setHideCursor] = React.useState(true);
    const [maxRetries, setMaxRetries] = React.useState(3);
    React.useEffect(() => {
        if (options?.maxRetries) {
            setMaxRetries(options.maxRetries);
        }
    }, [options?.maxRetries]);
    const handleInputChanged = (event) => {
        setInput((prev) => {
            if (cursorPosition >= prev.length) {
                setCursorPosition(event.target.value.length);
            }
            else {
                if (prev.length > event.target.value.length) {
                    setCursorPosition(cursorPosition - 1);
                }
                else {
                    setCursorPosition(cursorPosition + 1);
                }
            }
            return event.target.value;
        });
    };
    const changeCursorPos = (pos) => {
        if (inputRef.current) {
            inputRef.current.focus();
            inputRef.current.setSelectionRange(pos, pos);
            setCursorPosition(pos);
        }
    };
    const changeInput = (text) => {
        setInput(text);
        changeCursorPos(text.length);
    };
    const validateInputAndEnter = (text) => {
        if (options?.validator) {
            if (options.validator(text)) {
                handleEnter(text);
            }
            else {
                displayOutput([
                    {
                        content: options?.errorMessage || "[Invalid input]",
                        options: {
                            color: "error",
                            variant: "caption",
                        },
                    },
                ]);
                handleError("Invalid input");
            }
        }
        else {
            handleEnter(text);
        }
    };
    const keyDownEvents = {
        Enter: (event) => {
            displayOutput(generateOutputNode({
                prefix,
                prompt,
                text: hideCursor ? "[hidden]" : input,
            }));
            if (options?.allowEmpty) {
                validateInputAndEnter(input);
            }
            else {
                if (numTries < maxRetries) {
                    if (input.length > 0) {
                        validateInputAndEnter(input);
                    }
                    else {
                        displayOutput({
                            content: options?.retryMessage || "[Please enter a value]",
                            options: {
                                color: "primary",
                                variant: "caption",
                            },
                        });
                        setNumTries(numTries + 1);
                    }
                }
                else {
                    displayOutput({
                        content: options?.errorMessage || "[Max retries exceeded]",
                        options: { color: "error", variant: "caption" },
                    });
                    handleError("Max retries exceeded");
                }
            }
        },
        ArrowLeft: (event) => {
            if (cursorPosition > 0) {
                changeCursorPos(cursorPosition - 1);
            }
        },
        ArrowRight: (event) => {
            if (cursorPosition < input.length) {
                changeCursorPos(cursorPosition + 1);
            }
        },
        Tab: (event) => {
            event.preventDefault();
        },
        Escape: (event) => {
            if (input.length > 0) {
                setInput("");
            }
        },
    };
    const handleKeyDown = (event) => {
        const keyEvent = keyDownEvents[event.key];
        if (keyEvent) {
            keyEvent(event);
        }
    };
    React.useEffect(() => {
        if (isFocused) {
            if (inputRef.current) {
                focusInput();
                changeInput(inputRef.current.value);
            }
            else {
                blurInput();
            }
        }
    }, [isFocused]);
    React.useEffect(() => {
        console.log(options?.mask);
        if (options?.mask !== undefined) {
            setHideCursor(options.mask);
        }
    }, [options?.mask]);
    return (<>
      <div className="react-terminal__input">
        <div className="react-terminal__input-prefix">
          {prefix}
          {hideCursor && " (hidden)"}
        </div>
        <div className="react-terminal__input-prompt">{prompt}</div>
        <div className="react-terminal__input-content">
          <p>
            {input.split("").map((char) => {
            return hideCursor ? "*" : char;
        })}
          </p>
          {isFocused && !hideCursor && (<span className={`react-terminal__terminal-cursor blink ${cursorClassName || "cursor__box"}`} style={{
                left: `${cursorPosition}ch`,
            }}/>)}
        </div>
      </div>
      <div className="react-terminal__input-wrapper">
        <input ref={inputRef} type="password" value={input} onChange={handleInputChanged} onKeyDown={handleKeyDown} onFocus={focusInput} onBlur={blurInput}/>
      </div>
    </>);
};
export default PasswordInput;
