import { useCallback } from "react";

import type { ToolbarButtonProps, TreeNodeProps } from "@devowl-wp/react-folder-tree";
import { message } from "@devowl-wp/react-folder-tree";

import { useStores } from "../../store/stores.js";
import { TreeStore } from "../../store/tree.js";
import { __ } from "../../utils/i18n.js";

import type { SetStateAction } from "react";

type SetStateBoolean = (value: SetStateAction<boolean>) => void;

function useRenameNode(
    setIsCreatableLinkDisabled?: SetStateBoolean,
    setIsTreeLinkDisabled?: SetStateBoolean,
    setToolbarActiveButton?: (value: SetStateAction<string>) => void,
) {
    const { treeStore } = useStores();

    const handleRenameNode = useCallback(
        (
            shToolbarActiveButton: string,
            shIsCreatableLinkDisabled: boolean,
            shIsTreeLinkDisabled: boolean,
            nodeRename: TreeNodeProps["$rename"],
        ) => {
            // Make other nodes editable / not editable
            setIsCreatableLinkDisabled?.(shIsCreatableLinkDisabled);
            setIsTreeLinkDisabled?.(shIsTreeLinkDisabled);
            setToolbarActiveButton?.(shToolbarActiveButton);

            // Make selected node editable / not editable
            treeStore.selected.setRename(nodeRename);
        },
        [treeStore, setIsCreatableLinkDisabled, setIsTreeLinkDisabled, setToolbarActiveButton],
    );

    const handleRenameClick: ToolbarButtonProps["onClick"] = useCallback(
        () => handleRenameNode("rename", true, true, true),
        [handleRenameNode],
    );

    const handleRenameCancel: ToolbarButtonProps["onCancel"] = useCallback(
        () => handleRenameNode(undefined, false, false, undefined),
        [handleRenameNode],
    );

    const handleNodePressF2: TreeNodeProps["onNodePressF2"] = useCallback(
        ({ id }) => id !== TreeStore.ID_ALL && handleRenameClick(undefined),
        [handleRenameClick],
    );

    /**
     * Handle rename close and depending on the save state create the new node.
     */
    const handleRenameClose: TreeNodeProps["onRenameClose"] = useCallback(
        async (save, inputValue, { id, title }) => {
            if (save && inputValue.length && title !== inputValue) {
                const hide = message.loading(__('Renaming "%s"...', inputValue));
                try {
                    await treeStore.byId(+id).setTitle(inputValue);
                    message.success(__('"%s" successfully renamed.', inputValue));
                    handleRenameCancel(undefined, undefined);
                } catch (e) {
                    message.error((e as any).responseJSON.message);
                } finally {
                    hide();
                }
            } else {
                handleRenameCancel(undefined, undefined);
            }
        },
        [treeStore, handleRenameCancel],
    );

    return { handleRenameClick, handleRenameCancel, handleNodePressF2, handleRenameClose };
}

export { useRenameNode };
