import { world, system } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";


//FORMULARIOS
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        if (player.hasTag('mod_room')) {

            player.runCommandAsync("tag @s add ui");
            tunningCar(player);
        }
        if (player.hasTag('tp')) {
            player.runCommandAsync("tag @s remove tp");
            tpUi(player);
        }
        if (player.hasTag('edit_game')) {
            settingGame(player);
        }
        if (player.hasTag('info')) {
            player.runCommandAsync("tag @s remove info");
            infoUi(player);
        }
    }
}, 20);
//TUNNING FORM
function tunningCar(player) {
    player.runCommandAsync("tag @s remove mod_room");
    const customUi = new ActionFormData()
        .title("Tuning Room")
        .body("")
        .button("translate.text.paint", "textures/ui/color")
        .button("translate.text.glass", "textures/ui/glass")
        .button("translate.text.vinyl", "textures/ui/vinyl")
        .button("translate.text.spoiler", "textures/ui/spoiler")
        .button("translate.text.exhaust", "textures/ui/exhaust")
        .button("translate.text.roof", "textures/ui/roof")
        .button("translate.text.bumper", "textures/ui/bumper")
        .button("translate.text.hood", "textures/ui/hood")
        .button("translate.text.wheel", "textures/ui/wheel")
        .button("translate.text.horn", "textures/ui/horn")
        .button("exit", "textures/ui/hammer_l");
    customUi.show(player).then((response) => {
        if (response.canceled) {
            player.runCommandAsync("tag @s add mod_room");
            return;
        }
        const selectedButton = response.selection;

        switch (selectedButton) {
            case 0: // Paint button
                player.runCommandAsync("event entity @e[r=4] paint");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 1: // Glass button
                player.runCommandAsync("event entity @e[r=4] glass");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 2: // Vinyl button
                player.runCommandAsync("event entity @e[r=4] vinyl");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 3: // Spoiler button
                player.runCommandAsync("event entity @e[r=4] spoiler");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 4: // Exhaust button
                player.runCommandAsync("event entity @e[r=4] exhaust");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 5: // Roof button
                player.runCommandAsync("event entity @e[r=4] roof");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 6: // Bumper button
                player.runCommandAsync("event entity @e[r=4] bumper");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 7: // Hood button
                player.runCommandAsync("event entity @e[r=4] hood");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 8: // Wheel button
                player.runCommandAsync("event entity @e[r=4] wheel");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 9: // Horn button
                player.runCommandAsync("event entity @e[r=4] horn");
                player.runCommandAsync("tag @s remove mod_room");
                break;
            case 10: // exit button
                player.runCommandAsync("tag @s remove mod_room");
                player.runCommandAsync("camera @s fade time 0.5 1 0.5");
                player.runCommandAsync("event entity @s room_mod_false");
                break;
        }
    });
}

// TEST RACE FORM

function settingGame(player) {
    const maps = ["Iceberg", "Jungle", "Oasis", "Dimensions"];
    const modes = ["Normal", "TNT", "Collect"];
    const times = ["day", "night", "midnight"];

    const systemEntities = world.getDimension("overworld").getEntities({ families: ["system"] });
    if (systemEntities.length === 0) {
        player.sendMessage("⚠ No se encontró entidad 'system'");
        return;
    }

    const systemEntity = systemEntities[0];

    const currentMap = systemEntity.getProperty("rl_cr:map");
    const currentMode = systemEntity.getProperty("rl_cr:gamemode");

    const selectedMap = maps.findIndex(m => m.toLowerCase() === currentMap) || 0;
    const selectedMode = modes.findIndex(m => {
        if (m === "Normal" && currentMode === "normal") return true;
        if (m === "TNT" && currentMode === "explode") return true;
        if (m === "Collect" && currentMode === "collect") return true;
        return false;
    }) || 0;

    // obtener la hora del día y clasificarla
    const timeOfDay = world.getTimeOfDay();
    let selectedTime = 0;
    if (timeOfDay >= 0 && timeOfDay < 12000) {
        selectedTime = 0; // Day
    } else if (timeOfDay >= 12000 && timeOfDay < 18000) {
        selectedTime = 1; // Night
    } else {
        selectedTime = 2; // Midnight
    }

    const settingGame = new ModalFormData()
        .title("Setting Game")
        .dropdown("Map", [" Iceberg", " Jungle", " Oasis", " Dimensions"], selectedMap)
        .dropdown("Mode", [" Normal Race", " TNT", " Collect"], selectedMode)
        .dropdown("Time set", [" Day", " Night", " Midnight"], selectedTime);

    settingGame.show(player).then((response) => {
        if (response.canceled) {
            player.runCommandAsync("tag @s remove edit_game");
            return;
        }

        const mapIndex = response.formValues[0];
        const modeIndex = response.formValues[1];
        const timeIndex = response.formValues[2];

        const map = maps[mapIndex];
        const mode = modes[modeIndex];
        const time_set = times[timeIndex];

        player.runCommandAsync(`execute as @e[family=system] unless entity @e[family=system,has_property={rl_cr:game_state="ongame",rl_cr:game_state="finished"}] run event entity @s ${map}`);
        player.runCommandAsync(`execute as @e[family=system] unless entity @e[family=system,has_property={rl_cr:game_state="ongame",rl_cr:game_state="finished"}] run event entity @s ${mode}`);
        player.runCommandAsync(`execute as @e[family=system] unless entity @e[family=system,has_property={rl_cr:game_state="ongame",rl_cr:game_state="finished"}] run time set ${time_set}`);
        player.runCommandAsync("tag @s remove edit_game");
    });
}

//TP FORM
function tpUi(player) {
    const tpUi = new ActionFormData()
        .title("TP")
        .body("ui test")
        .button("lobby")
        .button("oasis")
        .button("iceberg")
        .button("jungle")
        .button("dimensions")
    tpUi.show(player).then((response) => {
        const selectedButton = response.selection;

        switch (selectedButton) {
            case 0:

                player.runCommandAsync("tp @s -104 -19 790");
                break;
            case 1:
                player.runCommandAsync("tp @s 126 -5 1367");
                break;
            case 2:
                player.runCommandAsync("tp @s 156 -10 277");
                break;
            case 3:
                player.runCommandAsync("tp @s 626 130 757");
                break;
            case 4:
                player.runCommandAsync("tp @s -1847 176 943");
                break;
        }
    });
}


//INFO

function infoUi(player) {
    const customUi = new ActionFormData()
        .title("INFO")
        .body("translate.text.ui_info")
        .button("Start Game")
        .button("Controls")
        .button("Game Mode")
        .button("Powerups")
    customUi.show(player).then((response) => {
        const selectedButton = response.selection;

        switch (selectedButton) {
            case 0:
                play_info(player);
                break;
            case 1:
                controls_info(player);
                break;
            case 2:
                gamemode_info(player);
                break;
            case 3:
                powerup_info(player);
                break;
        }
    });
}


function play_info(player) {
    const customUi = new ActionFormData()
        .title("Start Game")
        .body("translate.text.start_info")
        .button("");
    customUi.show(player).then((response) => {
        const selectedButton = response.selection;
        switch (selectedButton) {
            case 0:
                infoUi(player);
                break;
        }
    });
}
function controls_info(player) {
    const customUi = new ActionFormData()
        .title("Controls")
        .body("translate.text.controls_info")
        .button("")
    customUi.show(player).then((response) => {
        const selectedButton = response.selection;
        switch (selectedButton) {
            case 0:
                infoUi(player);
                break;
        }
    });
}

function gamemode_info(player) {
    const customUi = new ActionFormData()
        .title("Game Mode")
        .body("translate.text.gamemode_info")
        .button("");
    customUi.show(player).then((response) => {
        const selectedButton = response.selection;
        switch (selectedButton) {
            case 0:
                infoUi(player);
                break;
        }
    });
}

function powerup_info(player) {
    const customUi = new ActionFormData()
        .title("Power ups")
        .body("translate.text.powerups_info")
        .button("")
    customUi.show(player).then((response) => {
        const selectedButton = response.selection;
        switch (selectedButton) {
            case 0:
                infoUi(player);
                break;
        }
    });
}
