import { ActionFormData } from "@minecraft/server-ui";
import { system } 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";

export async function showApp(player){
    if (await checkDepletedBattery(player))
        return;

    let appStoreData = gld.getAppData("app_store");

    let availableApps = gld.appsForSale(player);
    
    let AppStoreForm = new ActionFormData().title(appStoreData.name);

    let allAppsPurchasedMsg = "All apps have been purchased; use them and enjoy the features they provide.\n\n" + 
        "§5Don't forget to give this Add-On a 5-star rating on the Marketplace.\n\n"+
        "§6            ⭐⭐⭐⭐⭐\n\n";
    
    let purchaseAppsMsg = "You can purchase premium apps and add them to your Smartphone. " 
        + "Once purchased, you can start using them and enjoy the features they provide.\n\nPurchase apps:\n";

    let bodyText = gld.getScreenTitle(player);
    bodyText += (availableApps.length === 0) ? allAppsPurchasedMsg : purchaseAppsMsg;
    AppStoreForm = AppStoreForm.body(bodyText);
    
    for(let appData of availableApps)
    {
        let costColor = wallet.canAfford(player, appData.cost) ? "§l§a" : "§l§c";
        AppStoreForm = AppStoreForm.button(`§l§b${appData.name}\n${costColor}Cost: ${appData.cost} ${gld.coinSymbol} ${costColor}§f`, appData.icon);
    }
    AppStoreForm = AppStoreForm.button("Back", "textures/goe/spa/ui/back");
        


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

        let playerPressed = response.selection;

        if (playerPressed < availableApps.length) 
        {
            let selectedAppData = availableApps[playerPressed];
            if (wallet.canAfford(player, selectedAppData.cost)) {
                player.playSound("goe_spa:purchase");
                player.addTag(gld.getAppTag(selectedAppData));
                utils.tellraw(player, "@s", `Purchased app: ${selectedAppData.name}`);
                // utils.tellraw(player, "@s", `§aSmartcoins balance: §6${wallet.getBalance(player)}${gld.coinSymbol}`);
                
                wallet.charge(player, selectedAppData.cost);

                // Show player title message
                player.onScreenDisplay.setTitle(" ", { subtitle: `Purchased app:\n${selectedAppData.name.substring(2)}`, stayDuration: 40, fadeInDuration: 0, fadeOutDuration: 0 });

                // Particle
                player.dimension.spawnParticle(selectedAppData.particle, player.location);

                // Hide ui and lock phone item in hand
                player.addTag("goe_spa_app_purchased");
                let ticksPassed = 0;
                const targetSlot = player.selectedSlotIndex;
                const interval = system.runInterval(() => {
                    if (ticksPassed === 0) {
                        inventory_utils.lockHeldItem(player);
                    }
                    ticksPassed += 5;
                    player.selectedSlotIndex = targetSlot;

                    if (ticksPassed < 40) {
                        return;
                    }

                    if (ticksPassed < 80) {
                        if (ticksPassed % 20 === 5)
                            player.playSound("goe_spa:downloading");
                        
                        const percentage = Math.min(Math.floor((ticksPassed - 40) / 30 * 100), 100);
                        const progressBar = utils.getProgressBar(percentage / 100, 10, "§a");
                        player.onScreenDisplay.setTitle(" ", { subtitle: `Downloading: ${percentage}%\n${progressBar}`, stayDuration: 20, fadeInDuration: 0, fadeOutDuration: 0 });
                        return;
                    }

                    if (ticksPassed < 120) {
                        if (ticksPassed % 20 === 5)
                            player.playSound("goe_spa:downloading");
                        
                        const percentage = Math.min(Math.floor((ticksPassed - 80) / 30 * 100), 100);
                        const progressBar =utils.getProgressBar(percentage / 100, 10, "§a");
                        player.onScreenDisplay.setTitle(" ", { subtitle: `Installing: ${percentage}%\n${progressBar}`, stayDuration: 20, fadeInDuration: 0, fadeOutDuration: 0 });
                        return;
                    }

                    if (ticksPassed == 120) {
                        player.playSound("goe_spa:app_installed");
                        utils.runPlayerCommand(player, "particle goe_spa:stars");
                    }

                    if (ticksPassed < 160) {
                        player.onScreenDisplay.setTitle(" ", { subtitle: `${selectedAppData.name.substring(2)}\n§finstalled!`, stayDuration: 20, fadeInDuration: 0, fadeOutDuration: 0 });
                        return;
                    }

                    inventory_utils.unlockHeldItem(player);
                    player.onScreenDisplay.setTitle("");
                    system.clearRun(interval);
                    player.removeTag("goe_spa_app_purchased");
                    main_menu(player);
                }, 5);
            } else {
                player.playSound("goe_spa:reject");
                showCantAffordForm(player, appStoreData, selectedAppData);
            }
                
        }
        else {
            player.playSound("goe_spa:button_click");
            main_menu(player);
        }
    });
}



async function showConfirmForm(player, appStoreData, selectedAppData) {
    const ConfirmForm = new ActionFormData()
        .title(appStoreData.name)
        .body(`${gld.getScreenTitle(player)}\nPlease confirm the purchase:\n\n${selectedAppData.name}\n\nCost: ${selectedAppData.cost} §6${gld.coinSymbol} §r\n\n`+
            `§eBalance:       §6${wallet.getBalance(player)}${gld.coinSymbol}§r\n` + 
            `§aNew Balance:  §6${wallet.getBalance(player) - selectedAppData.cost}${gld.coinSymbol}§r\n\n`)
        .button("§l§aConfirm", "textures/goe/spa/ui/confirm")
        .button("§l§cCancel", "textures/goe/spa/ui/cancel");

        ConfirmForm.show(player).then((response) => {
            inventory_utils.replacePhoneIfUIClosed(player, response);
        let playerPressed = response.selection;

        switch (playerPressed) {
            case 0:
                break;
            case 1:
                player.playSound("goe_spa:cancel");
                break;
        }
        main_menu(player);
    });
}

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

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

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

        main_menu(player);
    });
}
