import {ActionFormData} from "@minecraft/server-ui"
import {prettyName} from "cubc/mo_en/enchanthelpers"
import {ItemStack} from "@minecraft/server"
import {enchantsPerTier} from "cubc/mo_en/enchantinfo"

function getRandomElement(list) {
    return list[Math.floor(Math.random() * list.length)];
}

export function openAnvilMenu(player) {
    const form = new ActionFormData();

    form.title("Buy a book");

    let books = ["§4Common", "§6Rare", "§3Epic", "§5Legendary", "§dMythical"]
    let costs = [1, 1, 1, 2, 2];
    let minLevels = [10, 15, 20, 25, 30];

    let playerLevel = player.level;
    form.body(`Current level: §2${playerLevel}`);

    for (let i = 0; i < books.length; i++) {
        let bookTitle = books[i];
        let bookIcon = `enchanting_book_${i + 1}`;
        let cost = costs[i];
        let minLevel = minLevels[i];

        if (playerLevel >= minLevel) {
            form.button(`§l${bookTitle} Book\n§r§2Level: ${minLevel} | Cost: ${cost}L`, `textures/cubc/mo_en/items/icons/${bookIcon}`);
        } else {
            form.button(`§l${bookTitle} Book\n§r§cLevel: ${minLevel} | Cost: ${cost}L`, `textures/cubc/mo_en/items/icons/${bookIcon}`);
        }
    }
    form.show(player).then((response) => {
        if (response.canceled) {
            return;
        } else {
            let selectedLevel = minLevels[response.selection];
            if (playerLevel >= selectedLevel) {
                let possibleEnchants = enchantsPerTier[response.selection + 1];
                let enchantmentBook = getRandomElement(possibleEnchants);
                const itemStack = new ItemStack(`cubc_mo_en:${enchantmentBook}_book`);
                player.dimension.spawnItem(itemStack, player.location);
                player.sendMessage(`§e${prettyName(enchantmentBook, true)} Book received!`);
                player.runCommand(`xp -${costs[response.selection]}L @s`)
            } else {
                player.sendMessage(`§cNot enough levels`);
            }
            openAnvilMenu(player);
        }
    });
}
