import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { system, world, ItemStack, EnchantmentType } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import * as gld from "../gld";
import * as wallet from "../wallet";
import { showApp as main_menu, checkDepletedBattery } from "./main_menu"; 
import { showApp as finances } from "./bank";
import * as delivery from "./delivery";

let enchantmentStoreData = gld.getAppData("enchantment_store");

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    
    // Set layout
    const EnchantmentStoreForm = new ActionFormData().title(enchantmentStoreData.name);
    EnchantmentStoreForm.body( gld.getScreenTitle(player) + `Use this app to purchase useful enchantments.\n\n` );

    for (const enchantment of gld.enchantments) {
        let baseCost = enchantment.cost[0];
        let maxCost = enchantment.cost[enchantment.cost.length - 1];

        let costColor = wallet.canAfford(player, baseCost) ? "§l§a" : "§l§c";
        if (baseCost != maxCost)
            EnchantmentStoreForm.button(`§l${enchantment.name}\n${costColor}Cost: ${baseCost}-${maxCost} ${gld.coinSymbol}`, enchantment.icon);
        else
            EnchantmentStoreForm.button(`§l${enchantment.name}\n${costColor}Cost: ${baseCost} ${gld.coinSymbol}`, enchantment.icon);
    }

    EnchantmentStoreForm.button("Back", "textures/goe/spa/ui/back");

    // Display app
    EnchantmentStoreForm.show(player).then(result => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        if (result.canceled) return;
    
        player.playSound("goe_spa:button_click");

        if (result.selection < gld.enchantments.length) {
            displayEnchantmentPage(player, gld.enchantments[result.selection]);
            return;
        }
        
        main_menu(player);

    }).catch(error => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        utils.debug(error.message);
    });
}

async function displayEnchantmentPage(player, enchantment) {
    // Set layout
    const EnchantmentStoreForm = new ActionFormData().title(enchantmentStoreData.name);

    EnchantmentStoreForm.body(
        gld.getScreenTitle(player) +
        `§eEnchantment: ${enchantment.name}\n\n` + 
        `§bSelect level:§f\n` 
    );

    for (let i = 0; i < enchantment.cost.length; i++) {
        const cost = enchantment.cost[i];
        let costColor = wallet.canAfford(player, cost) ? "§l§a" : "§l§c";
        EnchantmentStoreForm.button(`§l§eLevel ${i + 1}\n${costColor}Cost: ${cost}${gld.coinSymbol}§f`, enchantment.icon);
    }

    EnchantmentStoreForm.button("Back", "textures/goe/spa/ui/back");

    // Display enchantment page
    EnchantmentStoreForm.show(player).then(async result => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        if (result.canceled) 
            return;

        // Get dropbox value
        let selected = result.selection;
        if (selected === enchantment.cost.length) { // Back is selected
            player.playSound("goe_spa:button_click");
            showApp(player);
            return;
        }

        const level = selected + 1;
        const cost = enchantment.cost[selected];
        const enchantmentName = enchantment.name + " " + utils.toRoman(level);

        if (!wallet.canAfford(player, cost)) {
            player.playSound("goe_spa:reject");
            showCantAffordForm(player, enchantmentName, 1, cost);
            return;
        }

        player.playSound("goe_spa:button_click");

        utils.tellraw(player, "@s", `Purchased enchantment: ${enchantment.name} ${utils.toRoman(level)}`);
        
        // Charge player coins
        wallet.charge(player, cost);

        delivery.sendDelivery(player, delivery.DELIVERY_TYPE.enchantment, enchantment.type, enchantment.name, level);
        
        player.playSound("goe_spa:purchase");

        showDeliveryPage(player);

    }).catch(error => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        utils.debug(error.message);
    });
}

export async function showDeliveryPage(player) {
    let DeliveryPage = new ActionFormData();
    DeliveryPage.title(enchantmentStoreData.name);
    DeliveryPage.body(
        gld.getScreenTitle(player) + 
        `Purchase completed successfully!\n\n` +
        `Your item will be delivered soon.\n\n`
    );

    DeliveryPage.button("Return to store", "textures/goe/spa/ui/back");

    DeliveryPage.show(player).then(result => {
        inventory_utils.replacePhoneIfUIClosed(player, result);
        if (result.canceled) return;

        showApp(player);
    });
}

async function showCantAffordForm(player, item, amount, cost) {
    const CantAffordForm = new ActionFormData();
    CantAffordForm.title(enchantmentStoreData.name);
    CantAffordForm.body(
        gld.getScreenTitle(player) +
        `\nNot enough Smartcoins (§6${gld.coinSymbol}§r).\n\n` +
        `  §l§5${item}§r\n\n` + 
        `§cCost:      ${cost} ${gld.coinSymbol}§r\n` + 
        `§4Missing:   ${cost - wallet.getBalance(player)} ${gld.coinSymbol}§r\n\n`
    );
    CantAffordForm.button("§eGet Smartcoins", gld.getAppData("bank").icon);
    CantAffordForm.button("Back", "textures/goe/spa/ui/back");

    CantAffordForm.show(player).then((response) => {
        player.playSound("goe_spa:button_click");

        if (response.selection == 0) {
            finances(player);
            return;
        }

        showApp(player);
    });
}