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 gearMarketData = gld.getAppData("gear_market");

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    // Set layout
    const GearMarketForm = new ActionFormData().title(gearMarketData.name);
    GearMarketForm.body( gld.getScreenTitle(player) + `§rUse this app to purchase useful gear.§f\n\n` );

    for (const gearGroup of gld.gear) {
        GearMarketForm.button(`${gearGroup.name}\n`, gearGroup.icon);
    }

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

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

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

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

async function showGearGroup(player, gearGroup) {
    // Set layout
    const GearGroupForm = new ActionFormData().title(gearMarketData.name);

    GearGroupForm.body( gld.getScreenTitle(player) + `§3Purchase gear:§f\n` );

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

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

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

        // Get selected index
        const selected = result.selection;
        if (selected === gearGroup.items.length) { // Back pressed
            player.playSound("goe_spa:button_click");
            showApp(player);
            return;
        }

        const selectedItem = gearGroup.items[selected];
        
        const itemType = selectedItem.id;
        const itemName = selectedItem.name;
        const cost = selectedItem.cost;

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

        player.playSound("goe_spa:button_click");

        utils.tellraw(player, "@s", `Purchased gear: ${selectedItem.name}`);

        // Charge player coins
        wallet.charge(player, cost);

        let selectedItemName = selectedItem.nameInPackage !== undefined ? selectedItem.nameInPackage : selectedItem.name;
        // Give item
        if (itemType === "minecraft:arrow")
            delivery.sendDelivery(player, delivery.DELIVERY_TYPE.gear, selectedItem.id, selectedItemName, 16);
        else
            delivery.sendDelivery(player, delivery.DELIVERY_TYPE.gear, selectedItem.id, selectedItemName, 1);
        
        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(gearMarketData.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(gearMarketData.name);
    CantAffordForm.body(
        gld.getScreenTitle(player) +
        `\nNot enough Smartcoins (§6${gld.coinSymbol}§r).\n\n` + 
        `  §l§e${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);
    });
}