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

const ZOMBIES_INFO = [
    {
        name: "Zomb",
        image: "textures/lv/zo/items/egg/zomb.png",
        description: "A basic zombie that has multiple variants and attacks slowly.",
        loot: ["Zombie Arm", "Knight Armor Pieces", "Rotten Flesh"],
        special: "None."
    },
    {
        name: "Small Zomb",
        image: "textures/lv/zo/items/egg/small_zomb.png",
        description: "A smaller and faster variant of the Zomb.",
        loot: ["Zombie Arm", "Knight Armor Pieces", "Rotten Flesh"],
        special: "Faster attacks."
    },
    {
        name: "Chubby",
        image: "textures/lv/zo/items/egg/chubby.png",
        description: "A fat zombie that is a bit more tanky than the normal Zomb.",
        loot: ["Zombie Arm", "Knight Armor Pieces", "Rotten Flesh"],
        special: "None."
    },
    {
        name: "Slapstick",
        image: "textures/lv/zo/items/egg/slapstick.png",
        description: "A tall zombie that has very long arms and legs.",
        loot: ["Frying Pan", "Pitchfork", "Knight Armor Pieces", "Rotten Flesh"],
        special: "High knockback damage."
    },
    {
        name: "Zombomb",
        image: "textures/lv/zo/items/egg/zombomb.png",
        description: "A fast zombie that explodes when too close, can also instantly explode on hit.",
        loot: ["Gunpowder", "Knight Armor Pieces", "Rotten Flesh"],
        special: "Explosive damage (No Block Damage)."
    },
    {
        name: "Slime Shooter",
        image: "textures/lv/zo/items/egg/slime_shooter.png",
        description: "A small slime spitting zombie.",
        loot: ["Poisonous Slime", "Knight Armor Pieces", "Rotten Flesh"],
        special: "Shoots poison projectiles."
    },
    {
        name: "Tanky",
        image: "textures/lv/zo/items/egg/tanky.png",
        description: "A huge zombie with a small rider on top, killing it will expose its rider.",
        loot: ["Stone Splinters", "Knight Armor Pieces", "Rotten Flesh"],
        special: "Very tanky, strong attacks."
    },
    {
        name: "Zomboss",
        image: "textures/lv/zo/items/egg/zomboss.png",
        description: "A strong boss that has multiple attack patterns and multiple phases, can be found in Abandoned Mansions in the Overworld.",
        loot: ["Emeralds", "Knight Armor Pieces", "Metal Scrap", "Diamonds", "Rotten Flesh"],
        special: "Tanky boss with multiple attacks and different phases."
    }
];

const ITEMS_INFO = [
    {
        name: "Knight Armor",
        image: "textures/lv/zo/items/knight_helmet.png",
        description: "A mediocre armor set that is dropped by zombies.",
        craft: ["Dropped by Zombies"]
    },
    {
        name: "Scrap Armor",
        image: "textures/lv/zo/items/scrap_helmet.png",
        description: "A mediocre armor set that can be obtained through meteors.",
        craft: ["Metal Scraps (Found in meteors)"]
    },
    {
        name: "Flashlight",
        image: "textures/lv/zo/items/flash_light.png",
        description: "A flashlight that can be used to light up the way in-front of you, can also be toggled on and off.",
        craft: ["Metal Scraps + Glowstone"]
    },
    {
        name: "Potato Launcher",
        image: "textures/lv/zo/items/potato_launcher.png",
        description: "A ranged weapon that shoots any kind of potato.",
        craft: ["Potato + Hopper + Dispenser + Lever"]
    },
    {
        name: "Slimy Slingshot",
        image: "textures/lv/zo/items/slime_slingshot.png",
        description: "A ranged weapon that shoots Poisonous Slime.",
        craft: ["Poisonous Slime + String + Iron Ingot + Stick"]
    },
    {
        name: "Tennisball Turret",
        image: "textures/lv/zo/items/tenis_turret.png",
        description: "A placeable turret that shoots tennisballs.",
        craft: ["Metal Scrap, Stone, Iron Ingots, Green Wool"]
    },
    {
        name: "Crossbow Turret",
        image: "textures/lv/zo/items/crossbow_turret.png",
        description: "A placeable turret that shoots arrows.",
        craft: ["Metal Scrap, Stone, Arrow, Planks"]
    },
    {
        name: "Zombie Slapper",
        image: "textures/lv/zo/items/zomb_slayer.png",
        description: "A melee weapon that has increased knockback.",
        craft: ["Zombie Arm, Rotten Flesh, Bone"]
    },
    {
        name: "Bear Trap",
        image: "textures/lv/zo/items/bear_trap.png",
        description: "A placeable trap that snaps once an entity steps on it.",
        craft: ["Metal Scrap, Stone Splinters"]
    },
    {
        name: "Barbed Wire",
        image: "textures/lv/zo/items/barbed_wire.png",
        description: "A placeable block that damages and slows entities inside of it.",
        craft: ["Metal Scrap, Stone Splinters"]
    }
    // Add more here
];

const scoreboardName = "lv_zo_global_toggles";

const OpenMenu = {
    async onUse(event) {
        const player = event.source;

        const menuForm = new ActionFormData()
            .title("§lZOMBIFIED GUIDE")
            .body("Welcome to the §c§lZOMBIFIED Info Menu§r! Explore new monsters, learn how to craft items and equipment.\n\n§c§oOr check out the official wiki on zombified.lvltcs.com")
            .button("Zombies", "textures/lv/zo/ui/zombies.png")
            .button("Items & Equipment", "textures/lv/zo/ui/items.png")
            .button("World & Events", "textures/lv/zo/ui/world.png")
            .button("Settings", "textures/lv/zo/ui/settings.png")
            .button("Feedback", "textures/lv/zo/ui/feedback.png");

        const response = await menuForm.show(player);
        if (response.canceled) return;

        switch (response.selection) {
            case 0:
                //Create a page layout that lists out a bunch of sub pages each having following information: Image, Name, Description, Loot Drops, Special
                await showZombiesPage(player);
                break;
            case 1:
                //Create a page layout that lists out a bunch of sub pages each having following information: Image, Name, Description, How To Craft
                await showItemsPage(player);
                break;
            case 2:
                //Create a page layout that is split between Biome Corruption and Structures: Biomes.. should basically have only a description same for Structures.
                await showBiomesPage(player);
                break;
            case 3:
                //Stays the Same
                await showSettingsPage(player);
                break;
            case 4:
                //Stays the Same
                await showFeedbackPage(player);
                break;
        }
    }
};

async function showSettingsPage(player) {
    try {
        await player.runCommandAsync(`scoreboard objectives add ${scoreboardName} dummy`);
    } catch { }

    // Get VFX toggle
    let vfx = true;
    try {
        const obj = world.scoreboard.getObjective(scoreboardName);
        const part = obj?.getParticipants().find(p => p.displayName === "toggle_vfx");
        vfx = part ? obj.getScore(part) === 1 : true;
    } catch { }

    // Get Horde Interval (defaults to 7)
    let hordeInterval = 7;
    try {
        const obj = world.scoreboard.getObjective(scoreboardName);
        const part = obj?.getParticipants().find(p => p.displayName === "slider_horde_night_interval");
        const score = part ? obj.getScore(part) : 7;
        if (typeof score === "number" && !isNaN(score)) {
            hordeInterval = Math.max(3, Math.min(9, score));
        }
    } catch { }

    // Get Zombie Difficulty (defaults to 0)
    let zombieDifficulty = 0;
    try {
        const obj = world.scoreboard.getObjective(scoreboardName);
        const part = obj?.getParticipants().find(p => p.displayName === "slider_zombie_difficulty");
        const score = part ? obj.getScore(part) : 0;
        if (typeof score === "number" && !isNaN(score)) {
            zombieDifficulty = Math.max(0, Math.min(2, score));
        }
    } catch { }

    const form = new ModalFormData()
        .title("§lSETTINGS")
        .toggle("VFX - Toggles Visual Effects §8(Might reduce lag)§r", vfx)
        .slider("Horde Night Interval §8(In days)§r", 3, 9, 1, hordeInterval)
        .slider("Zombie Difficulty §8(0=Normal, 2=Hard)§r", 0, 2, 1, zombieDifficulty)
        .submitButton("Submit");

    const result = await form.show(player);
    if (result.canceled) return;

    const vfxValue = result.formValues[0] ? 1 : 0;
    const intervalValue = Math.round(result.formValues[1]);
    const difficultyValue = Math.round(result.formValues[2]);

    try {
        await player.runCommandAsync(`scoreboard players set "toggle_vfx" ${scoreboardName} ${vfxValue}`);
        await player.runCommandAsync(`scoreboard players set "slider_horde_night_interval" ${scoreboardName} ${intervalValue}`);
        await player.runCommandAsync(`scoreboard players set "slider_zombie_difficulty" ${scoreboardName} ${difficultyValue}`);
        player.sendMessage(`§8[§6!§8]§7 Settings were updated!`);
    } catch (err) {
        console.warn("Error saving settings:", err);
    }
}





// Feedback page function
async function showFeedbackPage(player) {
    const feedback = new ActionFormData()
        .title("§lFEEDBACK")
        .body(
            "§c§lThank you§r for downloading our Zombified Add-On; we truly appreciate your support!\n" +
            "§7§oIf you encounter any bugs, issues, or have suggestions for future updates, feel free to reach out to us on any of our social media platforms or join our Discord community.\n\n" +
            "§e§lOur Socials:§r\n" +
            "§f§lInstagram: §r§7@levelatics\n" +
            "§f§lTwitter/X: §r§7@levelatics\n" +
            "§f§lYoutube: §r§7@levelatics\n\n" +
            "§e§lJoin our Community:§r\n" +
            "§f§lDiscord: §r§7@discord.levelatics.com\n"
        )
        .button("Back", "textures/lv/zo/ui/back.png");

    const result = await feedback.show(player);
    if (!result.canceled) {
        OpenMenu.onUse({ source: player }); // Go back to main
    }
}


async function showZombiesPage(player) {
    const form = new ActionFormData()
        .title("§lZOMBIES")
        .body("Select a zombie to view details.");

    for (const zombie of ZOMBIES_INFO) {
        form.button(zombie.name, zombie.image);
    }

    form.button("§cBack", "textures/lv/zo/ui/back.png"); // Add Back button

    const result = await form.show(player);
    if (result.canceled) return;

    if (result.selection === ZOMBIES_INFO.length) {
        await OpenMenu.onUse({ source: player }); // Go back to main menu
        return;
    }

    const selected = ZOMBIES_INFO[result.selection];
    await showZombieDetails(player, selected);
}


async function showZombieDetails(player, zombie) {
    const form = new ActionFormData()
        .title(`§l${zombie.name}`)
        .body(
            `§eDescription:\n§r${zombie.description}\n\n` +
            `§eLoot Drops:\n§r${zombie.loot.join(", ")}\n\n` +
            `§eSpecial Ability:\n§r${zombie.special}`
        )
        .button("Back");

    const result = await form.show(player);
    if (!result.canceled) await showZombiesPage(player);
}

async function showItemsPage(player) {
    const form = new ActionFormData()
        .title("§lITEMS & EQUIPMENT")
        .body("Select an item to view details. \n§bCrafting Items:§r§8 It is highly recommended to use the Crafting Guide inside the Crafting Table.");

    for (const item of ITEMS_INFO) {
        form.button(item.name, item.image);
    }

    form.button("§cBack", "textures/lv/zo/ui/back.png"); // Add Back button

    const result = await form.show(player);
    if (result.canceled) return;

    if (result.selection === ITEMS_INFO.length) {
        await OpenMenu.onUse({ source: player }); // Go back to main menu
        return;
    }

    const selected = ITEMS_INFO[result.selection];
    await showItemDetails(player, selected);
}


async function showItemDetails(player, item) {
    const form = new ActionFormData()
        .title(`§l${item.name}`)
        .body(
            `§eDescription:\n§r${item.description}\n\n` +
            `§eHow to Craft:\n§r${item.craft.join(" + ")}`
        )
        .button("Back");

    const result = await form.show(player);
    if (!result.canceled) await showItemsPage(player);
}

async function showBiomesPage(player) {
    const form = new ActionFormData()
        .title("§lBIOMES & STRUCTURES")
        .body("Explore corrupted biomes or mysterious structures.")
        .button("Biomes", "textures/lv/zo/ui/world.png")
        .button("Structures", "textures/lv/zo/ui/structures.png")
        .button("Horde Night", "textures/lv/zo/ui/horde_night.png")
        .button("§cBack", "textures/lv/zo/ui/back.png");

    const result = await form.show(player);
    if (result.canceled) return;

    switch (result.selection) {
        case 0:
            await showBiomesInfo(player);
            break;
        case 1:
            await showStructuresInfo(player);
            break;
        case 2:
            await showHordeNightInfo(player);
            break;
        case 3:
            await OpenMenu.onUse({ source: player });
            break;
    }
}

async function showBiomesInfo(player) {
    const form = new ActionFormData()
        .title("§lCORRUPTED BIOMES")
        .body(
            "§7The world is slowly being corrupted, forming infected patches across the land.\n\n" +
            "§cThe Corrupted Forest§7 has a reddish tint and appears lifeless, yet a strange new type of tree grows within it.\n" +
            "§cThe Corrupted Caves§7 are green- and brown-tinted underground areas filled with decayed blocks and scattered bones.\n\n" +
            "Each biome is procedurally infected and contains unique enemies."
        )

        .button("§cBack", "textures/lv/zo/ui/back.png");

    const result = await form.show(player);
    if (!result.canceled) await showBiomesPage(player);
}

async function showStructuresInfo(player) {
    const form = new ActionFormData()
        .title("§lSTRUCTURES")
        .body(
            "§7These rare landmarks offer valuable loot,\nbut are crawling with zombies.\n\n" +
            "§cThere are 8 unique structures to discover — most are found in forests, plains, and savannas."
        )

        .button("§cBack", "textures/lv/zo/ui/back.png");

    const result = await form.show(player);
    if (!result.canceled) await showBiomesPage(player);
}

async function showHordeNightInfo(player) {
    const form = new ActionFormData()
        .title("§lHORDE NIGHT")
        .body(
            "§7Every few days (configurable in Settings), a Horde Night will occur.\n\n" +
            "Massive waves of monsters will spawn, testing your survival skills. Be prepared — these nights offer a great challenge and will reveal whether you're truly ready for the apocalypse."
        )

        .button("§cBack", "textures/lv/zo/ui/back.png");

    const result = await form.show(player);
    if (!result.canceled) await showBiomesPage(player);
}

export default OpenMenu;
