import { useCallback } from "react";

import type { ToolbarButtonProps } from "@devowl-wp/react-folder-tree";
import { Popconfirm, 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 { useHandleSelect } from "./useHandleSelect.js";

function useTrashNode(handleSelect: ReturnType<typeof useHandleSelect>) {
    const { treeStore } = useStores();

    /**
     * Handle trashing of a category. If the category has subcategories, trashing is forbidden.
     */
    const handleTrash: Popconfirm["onConfirm"] = useCallback(async () => {
        const { selected } = treeStore;

        // Check if subdirectories
        if (selected.childNodes.filter((n) => n.$visible).length) {
            return message.error(__('You can not delete "%s" because it contains subcategories.', [selected.title]));
        }

        const hide = message.loading(__('Deleting "%s"...', selected.title));
        try {
            await selected.trash();
            message.success(__('"%s" successfully deleted.', selected.title));

            // Select parent
            handleSelect(selected.parent?.id || TreeStore.ID_ALL);
        } catch (e) {
            message.error((e as any).responseJSON.message);
        } finally {
            hide();
        }
    }, [treeStore, handleSelect]);

    /**
     * When opening the trash symbol in the toolbar do a Popconfirm instead of simple click.
     */
    const handleTrashModifier: ToolbarButtonProps["modifier"] = useCallback(
        (body) => {
            const { selected, selectedId } = treeStore;

            return selected && selectedId !== TreeStore.ID_ALL ? (
                <Popconfirm
                    overlayStyle={{ maxWidth: 254 }}
                    placement="bottom"
                    onConfirm={handleTrash}
                    title={__(
                        'Are you sure you want to delete "%s"? Note: The posts in this category will NOT be deleted automatically.',
                        [selected.title],
                    )}
                    okText={__("OK")}
                    cancelText={__("Cancel")}
                >
                    {body}
                </Popconfirm>
            ) : (
                body
            );
        },
        [handleTrash],
    );

    return { handleTrash, handleTrashModifier };
}

export { useTrashNode };
