import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { world } from "@minecraft/server";
import * as utils from "../utils";
import * as inventory_utils from "../inventory_utils";
import * as gld from "../gld";
import * as vector3 from "../vector3";
import { showApp as main_menu, checkDepletedBattery } from "./main_menu"; 

const mobDetectorName = gld.getAppData("mob_detector");

const DEFAULT_RADIUS = 30;
const MIN_RADIUS = 10;
const MAX_RADIUS = 60;

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

    let detectionRadius = player.getDynamicProperty("goe_spa_mob_radius");
    if (!detectionRadius)
        detectionRadius = DEFAULT_RADIUS;

    //let coordsNote = world.gameRules.showCoordinates ? "" : "§eNote:§f use the §bSettings App§f to show your coordinates.\n";
    let mobList = await getMobs(player, detectionRadius);
    if(!mobList || mobList === "")
		mobList = "No nearby mobs found\n";
    mobList = "--------------------\n"+mobList+" \n";

    let playerCoins = player.getDynamicProperty("goe_spa_coins");

    const MobDetectorApp = new ActionFormData()
        .title(mobDetectorName.name)
        .body(
            `${gld.getScreenTitle(player)}` +
            `§bDetection range:§f     ${detectionRadius} blocks.§r\n` +
            `§bCurrent coordinates:§f ${vector3.copyFloor(player.location).toCommandFloor()}§r\n`
            + mobList
        )
        .button("Detection Radius", "textures/goe/spa/ui/game_settings")
        .button("Back", "textures/goe/spa/ui/back");

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

        switch(playerPressed) {
        case 0:
            player.playSound("goe_spa:button_click");
            showSettingsForm(player, detectionRadius);
            break;

        case 1:
            player.playSound("goe_spa:button_click");
            main_menu(player)
            break;
        }
    })
}

async function getMobs(player, detectionRadius) {
    let allMobs = player.dimension.getEntities({
        location: player.location,
        maxDistance: detectionRadius,
        closest : 20
    }).filter(entity => 
        entity.typeId !== "minecraft:player" && 
        entity.typeId !== "minecraft:item" && 
        entity.typeId !== "goe_spa:biome_check" &&
        entity.typeId !== "minecraft:armor_stand"); // Add mobs to ignore

    // Sort the mobs by distance from the player
    allMobs.sort((a, b) => {
        const distanceA = vector3.distance(player.location, a.location);
        const distanceB = vector3.distance(player.location, b.location);
        return distanceA - distanceB;
    });
    
    // Format the list
    const mobList = allMobs.map(mob => {
        const { x, y, z } = mob.location;
        let mobType = mob.typeId;

        if (mobType.startsWith('minecraft:')) {
            mobType = mobType.replace('minecraft:', '');
        } else {
            mobType = mobType.replace('goe_spa:', '');
        }
        // Replace underscores with spaces
        mobType = mobType.replace(/_/g, ' ');

        // Capitalize the first letter of the mob type
        mobType = mobType.charAt(0).toUpperCase() + mobType.slice(1);

        // Calculate the distance from the player to the mob
        const distance = vector3.distance(player.location, mob.location);

        // Determine the direction relative to the player
        let direction = '';
        const dx = x - player.location.x;
        const dz = z - player.location.z;
        
        if (Math.abs(dx) > Math.abs(dz)) {
            direction = dx > 0 ? 'East' : 'West';
        } else {
            direction = dz > 0 ? 'South' : 'North';
        }

        return (
            `§fDetected §b${mobType} §fat §e${Math.round(x)} ${Math.round(y)} ${Math.round(z)}§f\n`
        );
    }).join('');

    return mobList;
}

async function showSettingsForm(player, detectionRadius) {
    const SettingsForm = new ModalFormData().title(mobDetectorName.name)
        .slider(gld.getScreenTitle(player) + 
            "§3Detection radius", MIN_RADIUS, MAX_RADIUS, 1, detectionRadius);

    SettingsForm.show(player).then(formData => {
        inventory_utils.replacePhoneIfUIClosed(player, formData);
        if (formData.formValues)
        {
            player.playSound("goe_spa:submit");
            let newDetectionRadius = formData.formValues[0];
            player.setDynamicProperty("goe_spa_mob_radius", newDetectionRadius);
            showApp(player);
        }   
    });
}