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

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;
    // Set layout
    const FoodStoreForm = new ActionFormData().title(foodStoreData.name);
    FoodStoreForm.body( gld.getScreenTitle(player) + `Use this app to purchase new types of food.\n\n` );

    for (const food of gld.foods) {
        let baseCost = food.cost;

        let costColor = wallet.canAfford(player, baseCost) ? "§l§a" : "§l§c";    
        FoodStoreForm.button(`§l§2${food.name} §r§l(${food.restores}x\ue100)\n${costColor}Cost: §l§6${baseCost}x${gld.coinSymbol}`, food.icon);
    }

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

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

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

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

async function displayFoodPage(player, food) {
    // Set layout
    const FoodStoreForm = new ActionFormData().title(foodStoreData.name);

    const baseCost = food.cost;

    FoodStoreForm.body(
        gld.getScreenTitle(player) +
        `§2Food:§r ${food.name} §r(${food.restores}x\ue100)\n\n` + 
        `§3Select amount:§f\n` 
    );

    let cost = baseCost;
    let costColor = wallet.canAfford(player, cost) ? "§l§a" : "§l§c";
    FoodStoreForm.button(`§l§6Amount: 1 ${costColor}\nCost: ${cost}${gld.coinSymbol}§f`, food.icon);

    cost = baseCost * 16;
    costColor = wallet.canAfford(player, cost) ? "§l§a" : "§l§c";
    FoodStoreForm.button(`§l§6Amount: 16 ${costColor}\nCost: ${cost}${gld.coinSymbol}§f`, food.icon);

    cost = baseCost * 64;
    costColor = wallet.canAfford(player, cost) ? "§l§a" : "§l§c";
    FoodStoreForm.button(`§l§6Amount: 64 ${costColor}\nCost: ${cost}${gld.coinSymbol}§f`, food.icon);

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

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

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

        const foodName = food.name;

        let amount = 1;
        if (selected === 1) amount = 16;
        else if (selected === 2) amount = 64;

        cost = baseCost * amount;
        if (!wallet.canAfford(player, cost)) {
            player.playSound("goe_spa:reject");
            showCantAffordForm(player, foodName, amount, cost);
            return;
        }

        player.playSound("goe_spa:button_click");

        utils.tellraw(player, "@s", `Purchased food: ${food.name}§r (Amount: ${amount})`);

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

        delivery.sendDelivery(player, delivery.DELIVERY_TYPE.food, food.id, food.name, amount);

        player.playSound("goe_spa:purchase");

        showDeliveryPage(player);

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

async function showCantAffordForm(player, item, amount, cost) {
    const CantAffordForm = new ActionFormData();
    CantAffordForm.title(foodStoreData.name);
    CantAffordForm.body(
        gld.getScreenTitle(player) +
        `\nNot enough Smartcoins (§6${gld.coinSymbol}§r)\n\n` + 
        `  §l§2${item} §r§l(Amount: ${amount}) §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);
    });
}

export async function showDeliveryPage(player) {
    let DeliveryPage = new ActionFormData();
    DeliveryPage.title(foodStoreData.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);
    });
}