import {
    ItemComponentTypes
} from "@minecraft/server";
import {applyBook} from "cubc/mo_en/enchants"
import {ActionFormData} from "@minecraft/server-ui"
import {bookApplicable, functional_name, getCustomEnchants, intToRoman, prettyName} from "cubc/mo_en/enchanthelpers"
import {bookInfo, itemList} from "cubc/mo_en/enchantinfo"
import {getEnchantLevel, getPlayerItems, isEnchantable, getTextureName} from "cubc/mo_en/enchanthelpers"


function openBookMenu(player, item_to_enchant, replaceItemFunction) {
    const form = new ActionFormData();
    const container = player.getComponent('inventory')?.container;

    const item_name = prettyName(item_to_enchant.typeId);

    let buttonText = item_to_enchant.nameTag ?? item_name;

    form.title("Enchant Menu");
    form.body(`Select enchantment to apply to ${buttonText}`);

    let books = [];

    for (let i = 0; i < container.size; i++) {
        const item = container.getItem(i);

        if (!item || !(item.typeId.includes('cubc_mo_en:') && item.typeId.includes('book')) || item.typeId.includes('page')) {
            continue;
        }
        if (!bookApplicable(item, item_to_enchant)) {
            continue
        }

        books.push(item);

        let extra_description = "";

        if (getEnchantLevel(item_to_enchant, bookInfo[item.typeId]["enchantName"]) === bookInfo[item.typeId]["maxLevel"]) {
            extra_description = "\n§2(MAX)"
        }

        form.button(prettyName(item.typeId, true).replace(" Book", "") + extra_description, `textures/cubc/mo_en/items/icons/${bookInfo[item.typeId]["texture"]}`);

    }

    if (books.length === 0) {
        player.sendMessage(`§cNo compatible books in inventory`);
        openEnchantMenu(player);
    } else {
        form.show(player).then((response) => {
            if (response.canceled) {
            } else {
                if (applyBook(player, books[response.selection], item_to_enchant)) {
                    replaceItemFunction(item_to_enchant);
                    player.runCommand(`clear @s[m=!creative] ${books[response.selection].typeId} -1 1`)
                }
                openEnchantMenu(player);
            }
        });
    }
}

export function openEnchantMenu(player) {
    const form = new ActionFormData();
    form.title("Enchant Menu");
    form.body("Select item to enchant");

    let menu_items = [];
    let items = getPlayerItems(player);

    for (let i = 0; i < items.length; i++) {
        const item = items[i]["item"];

        if (!item || !isEnchantable(item)) {
            continue;
        }

        menu_items.push(items[i]);
        const enchantments = item.getComponent(ItemComponentTypes.Enchantable).getEnchantments();

        let enchantment_list = []
        for (const enchant of enchantments) {
            enchantment_list.push(`${prettyName(enchant.type.id)} ${intToRoman(enchant.level)}`)
        }
        for (const enchant of getCustomEnchants(item)) {
            enchantment_list.push(`${prettyName(enchant.enchant)} ${intToRoman(enchant.level)}`)
        }

        const item_name = prettyName(item.typeId);

        let buttonText = item.nameTag ?? item_name;

        if (enchantment_list.length > 0) {
            buttonText += `\n§o§3${enchantment_list.join(', ')}`;
        }

        form.button(buttonText, `${getTextureName(functional_name(item_name))}`);
    }

    if (menu_items.length === 0) {
        form.body("No items in inventory to enchant");
        form.button("Cancel");
        form.show(player).then((response) => {});
    } else {
        form.show(player).then((response) => {
            if (response.canceled) {
            } else {
                openBookMenu(player, menu_items[response.selection]["item"], menu_items[response.selection]["replaceItemFunction"]);
            }
        });
    }

}