import {
    EntityComponentTypes,
    EntityTameableComponent,
    ItemStack,
    system,
} from "@minecraft/server";
import { ActionFormData, FormCancelationReason, MessageFormData } from "@minecraft/server-ui";
import { Bosses } from "../data/bosses";

/**
 *
 * @param {Player} player
 * @param {ItemStack} item
 */
export function lichSpellbookMenu(player, item) {
    const itemToUse = item;
    /**
     * @type {ActionFormData}
     */
    const UI = new ActionFormData();
    UI.title("Lich Spellbook");

    const buttonActions = [];

    const bossArray = Array.from(Bosses);

    Bosses.forEach((boss) => {
        // console.warn(JSON.stringify(boss))
        if (player.getDynamicProperty(boss.prop) == true) {
            UI.button(boss.name);
            buttonActions.push({
                exec: () => {
                    confirmationMenu(player, boss, itemToUse);
                },
            });
        }
    });

    UI.button("Close");

    UI.show(player).then((response) => {
        if (response.canceled || response.cancelationReason == FormCancelationReason.UserClosed) {
            return;
        }

        if (response.selection < buttonActions.length) {
            buttonActions[response.selection].exec();
        }
    });
}

/**
 *
 * @param {Player} player
 * @param {{name:string,typeId:string,prop:string}} boss
 * @param {ItemStack} item
 */
function confirmationMenu(player, boss, item) {
    const UI = new MessageFormData();
    UI.title("Spawn Mob?");

    UI.body("Are you sure you want to spawn the mob now?");

    UI.button1("Confirm");
    UI.button2("Cancel");
    UI.show(player).then((response) => {
        if (response.canceled || response.cancelationReason == FormCancelationReason.UserClosed) {
            return;
        }

        if (response.selection == 0) {
            player.playSound("mob.evocation_illager.cast_spell", {
                volume: 100,
                pitch: 1,
            });

            player.spawnParticle("ns_rh:lich", player.location);

            summonRessurectedMob(player, boss.typeId);
        }
        if (response.selection == 1) {
            lichSpellbookMenu(player);
        }
    });
}

/**
 *
 * @param {Player} player
 * @param {string} entityId
 */
function summonRessurectedMob(player, entityId) {
    const summonedMobs = player.dimension.getEntities({
        location: player.location,
        tags: ["lich_spellbook_summon"],
    });

    const summonedBoss = summonedMobs.some((mob) => {
        /**
         * @type {EntityTameableComponent}
         */
        const tameable = mob.getComponent(EntityComponentTypes.Tameable);

        if (!tameable) return false;

        if (!tameable.isTamed) return false;

        const owner = tameable.tamedToPlayer;

       // console.warn(owner.name);

        if (owner && owner.id === player.id) {
            return true;
        }
    });

    if (summonedBoss) {
        player.sendMessage("You already have a summoned mob!");
        return false;
    }

    const mob = player.dimension.spawnEntity(entityId, player.location);

    mob.triggerEvent("self:tameable");

    mob.triggerEvent("self:ressurected_spawned");

    mob.nameTag = "Companion";

    mob.addTag("summoned");

    mob.addTag("lich_spellbook_summon");

    system.runTimeout(() => {
        /**
         * @type {EntityTameableComponent}
         */
        const tameable = mob.getComponent(EntityComponentTypes.Tameable);

        if (tameable) {
            tameable.tame(player);
        }
    }, 0.1 * 20);
}
