import React from "react";
import reducers, { inputReducerInitialState, commandReducerInitialState, childrenReducerInitialState, } from "../store/reducers/index";
import { commandActions, inputActions, outputActions, childrenActions, } from "../store/actions/index";
import Text from "../components/Output/Text";
const useTerminal = ({ userCommands, cursor, children, welcomeMessage, }) => {
    /* @INFO: Output Reducer */
    const [output, dispatchOutput] = React.useReducer(reducers.outputReducer, []);
    /* @INFO: Input Reducer */
    const [inputState, dispatchInputState] = React.useReducer(reducers.inputReducer, inputReducerInitialState);
    /* @INFO: Terminal Commands */
    const [commands, dispatchCommands] = React.useReducer(reducers.commandReducer, commandReducerInitialState);
    /* @INFO: Children States */
    const [childrenState, dispatchChildrenState] = React.useReducer(reducers.childrenReducer, childrenReducerInitialState);
    const [openChild, setOpenChild] = React.useState(null);
    /* @INFO: Cursor Class Name */
    const cursorClassName = cursor === "block"
        ? "cursor__box"
        : cursor === "bar"
            ? "cursor__line"
            : cursor === "underline"
                ? "cursor__underline"
                : "cursor__box";
    /* @INFO: Terminal Refs */
    const inputRef = React.useRef(null);
    const scrollRef = React.useRef(null);
    /* @INFO: Internal Functions */
    const scrollToBottom = () => {
        if (scrollRef.current) {
            scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
    };
    const registerCommands = (commands) => {
        dispatchCommands(commandActions.addCommands(commands));
    };
    React.useEffect(() => {
        scrollToBottom();
    }, [output]);
    React.useEffect(() => {
        if (userCommands)
            registerCommands(userCommands);
    }, [userCommands]);
    React.useEffect(() => {
        if (children) {
            const childrenArray = React.Children.toArray(children);
            const fullScreenChildrenObject = {};
            childrenArray.forEach((child) => {
                if (!React.isValidElement(child)) {
                    console.error("Invalid child passed to Terminal");
                }
                if (typeof child?.type === "string") {
                    console.error("Invalid child passed to Terminal");
                }
                const type = child
                    .type;
                if (type.name && type.name === "FullscreenOutput") {
                    const { path, unmountOnExit } = child.props;
                    fullScreenChildrenObject[path] = {
                        component: child,
                        unmountOnExit,
                        open: false,
                    };
                }
            });
            dispatchChildrenState(childrenActions.setFullscreenChildren(fullScreenChildrenObject));
        }
    }, [children]);
    React.useEffect(() => {
        if (output.length !== 0)
            return;
        if (welcomeMessage) {
            if (React.isValidElement(welcomeMessage)) {
                dispatchOutput(outputActions.addOutput(welcomeMessage));
            }
            else if (typeof welcomeMessage === "string") {
                dispatchOutput(outputActions.addOutput(<Text variant="body1" color="primary">
              {welcomeMessage}
            </Text>));
            }
            else {
                console.warn("Invalid welcomeMessage type. welcomeMessage must be a string or a ReactNode.");
            }
        }
        dispatchOutput(outputActions.addOutput({
            content: "Type 'help' to see available commands.",
            options: {
                variant: "caption",
                color: "primary",
            },
        }));
    }, []);
    /* @INFO: Terminal Functions */
    const displayOutput = (data) => {
        dispatchOutput(outputActions.addOutput(data));
    };
    const clearOutput = () => {
        dispatchOutput(outputActions.clearOutput());
    };
    const userInput = async (prompt, options) => {
        return new Promise((resolve, reject) => {
            dispatchInputState(inputActions.setTextInput({
                prefix: !options.allowEmpty ? prompt : `${prompt} (empty to skip)`,
                prompt: "",
                handleEnter: (text) => {
                    dispatchInputState(inputActions.resetInput());
                    resolve(text);
                },
                handleError: (error) => {
                    dispatchInputState(inputActions.resetInput());
                    reject(error);
                },
                options,
            }));
            scrollToBottom();
        });
    };
    const userPassword = async (prompt, options) => {
        return new Promise((resolve, reject) => {
            dispatchInputState(inputActions.setPasswordInput({
                prefix: !options.allowEmpty ? prompt : `${prompt} (empty to skip)`,
                prompt: "",
                handleEnter: (password) => {
                    dispatchInputState(inputActions.resetInput());
                    resolve(password);
                },
                handleError: (error) => {
                    dispatchInputState(inputActions.resetInput());
                    reject(error);
                },
                options,
            }));
            scrollToBottom();
        });
    };
    const userConfirm = async (prompt, options) => {
        return new Promise((resolve, reject) => {
            dispatchInputState(inputActions.setBooleanInput({
                prefix: prompt,
                prompt: "",
                handleEnter: (choice) => {
                    dispatchInputState(inputActions.resetInput());
                    resolve(choice);
                },
                handleError: (error) => {
                    dispatchInputState(inputActions.resetInput());
                    reject(error);
                },
                options,
            }));
            scrollToBottom();
        });
    };
    const userSelect = async (prompt, options) => {
        return new Promise((resolve, reject) => {
            dispatchInputState(inputActions.setSelectInput({
                prefix: prompt,
                prompt: "",
                handleEnter: (choice) => {
                    dispatchInputState(inputActions.resetInput());
                    resolve(choice);
                },
                handleError: (error) => {
                    dispatchInputState(inputActions.resetInput());
                    reject(error);
                },
                options,
            }));
            scrollToBottom();
        });
    };
    const openFullscreen = (path) => {
        if (openChild) {
            console.error("Cannot open multiple fullscreen at once");
            return;
        }
        dispatchChildrenState(childrenActions.openFullscreenChildren(path));
        setOpenChild(path);
        dispatchInputState(inputActions.disableInput());
    };
    const closeFullscreen = () => {
        if (!openChild) {
            console.error("No fullscreen open");
            return;
        }
        dispatchChildrenState(childrenActions.closeFullscreenChildren(openChild));
        setOpenChild(null);
        setTimeout(() => {
            dispatchInputState(inputActions.resetInput());
        }, 100);
    };
    const startLoading = (data) => {
        dispatchInputState(inputActions.setLoading({
            text: data?.text || "Loading...",
            type: data?.type || "bar",
        }));
    };
    const stopLoading = (args) => {
        dispatchInputState(inputActions.resetInput());
        displayOutput([
            {
                content: args?.status === "success" ? "✔" : status === "error" ? "✖" : "◯",
                options: {
                    variant: "caption",
                    color: args?.status === "success"
                        ? "success"
                        : status === "error"
                            ? "error"
                            : "secondary",
                },
            },
            {
                content: args?.message ||
                    `${inputState?.state?.text} ${args?.status === "success"
                        ? "succeeded"
                        : args?.status === "error"
                            ? "failed"
                            : "completed"}`,
                options: {
                    variant: "body2",
                    color: "primary",
                },
            },
        ]);
    };
    const utils = {
        displayOutput,
        clearScreen: clearOutput,
        input: userInput,
        password: userPassword,
        confirm: userConfirm,
        select: userSelect,
        openFullscreen,
        closeFullscreen,
        startLoading,
        stopLoading,
    };
    Object.freeze(utils);
    const handleCommand = (input) => {
        const [trigger, ...args] = input.split(" ");
        const commandFunction = commands[trigger];
        if (!commandFunction)
            displayOutput({
                content: `Command not found: ${trigger}`,
                options: {
                    variant: "body1",
                    color: "error",
                },
            });
        else {
            if (trigger === "help") {
                commandFunction.callback(utils, args)(commands);
            }
            else {
                commandFunction.callback(utils, args);
            }
        }
    };
    const focusInput = () => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
        dispatchInputState(inputActions.setIsFocused(true));
    };
    const blurInput = () => {
        if (inputRef.current) {
            inputRef.current.blur();
        }
        dispatchInputState(inputActions.setIsFocused(false));
    };
    return {
        output,
        inputState,
        inputRef,
        scrollRef,
        commands,
        childrenState,
        handleCommand,
        focusInput,
        blurInput,
        cursorClassName,
        displayOutput: utils.displayOutput,
        closeFullscreen: utils.closeFullscreen,
    };
};
export default useTerminal;
