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

class MonsterAndBossGuide {
    static openMenu(source) {
        this.showMainMenu(source);
    }

    static showMainMenu(player) {
        const menuForm = new ActionFormData()
            .title("§lMONSTERS GUIDE")
            .body("Welcome to the §c§lMONSTERS Info Menu§r! Explore new monsters, learn how to craft items, and how to summon bosses.\n\n§c§oOr check out the official wiki on monsters.lvltcs.com")
            .button("Monsters", "textures/lv/mo/ui/monsters.png")
            .button("Bosses", "textures/lv/mo/ui/bosses.png")
            .button("Craftables", "textures/lv/mo/ui/craftables.png")
            .button("Settings", "textures/lv/mo/ui/settings.png")
            .button("Feedback", "textures/lv/mo/ui/feedback.png");

        menuForm.show(player).then((response) => {
            if (response.canceled) return;

            switch (response.selection) {
                case 0:
                    this.showMonstersMenu(player);
                    break;
                case 1:
                    this.showBossesMenu(player);
                    break;
                case 2:
                    this.showCraftablesPage(player);
                    break;
                case 3:
                    this.showSettingsPage(player);
                    break;
                case 4:
                    this.showFeedbackPage(player);
                    break;
            }
        });
    }
    static showFeedbackPage(player) {
        const feedbackPage = new ActionFormData()
            .title("§lFEEDBACK")
            .body(
                "§c§lThank you§r for downloading our Monsters 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 to Main", "textures/lv/mo/ui/back.png");

        feedbackPage.show(player).then((response) => {
            if (response.canceled) return;

            if (response.selection === 0) {
                this.showMainMenu(player);
            }
        });
    }
    static async showSettingsPage(player) {
        const scoreboardName = "global_toggles";
        const sawhopperKey = "toggle_sawhopper";
        const lizoredKey = "toggle_lizored";
        const spookKey = "toggle_spook";
        const bubblewingKey = "toggle_bubblewing";

        // Ensure scoreboard exists
        try {
            await player.runCommandAsync(`scoreboard objectives add ${scoreboardName} dummy`);
        } catch (e) {
            // Ignore if already exists
        }

        // Helper to get a toggle value
        const getToggleValue = (key) => {
            try {
                const objective = world.scoreboard.getObjective(scoreboardName);
                const participant = objective?.getParticipants().find(p => p.displayName === key);
                return participant ? objective.getScore(participant) === 1 : true; // Default true
            } catch (err) {
                console.warn(`Couldn't read toggle "${key}", defaulting to true:`, err);
                return true;
            }
        };

        const sawhopperDefault = getToggleValue(sawhopperKey);
        const lizoredDefault = getToggleValue(lizoredKey);
        const spookDefault = getToggleValue(spookKey);
        const bubblewingDefault = getToggleValue(bubblewingKey);

        const settingsPage = new ModalFormData()
            .title("§lSETTINGS")
            .toggle("Sawhopper - Enables Eating Bark Mechanic", sawhopperDefault)
            .toggle("Lizored - Enables Eating Dripstone Mechanic", lizoredDefault)
            .toggle("Spook - Toggles if Spooks can spawn", spookDefault)
            .toggle("Bubblewing - Toggles if Bubblewing can spawn", bubblewingDefault)
            .submitButton("Submit");

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

        const sawhopperToggle = response.formValues[0];
        const lizoredToggle = response.formValues[1];
        const spookToggle = response.formValues[2];
        const bubblewingToggle = response.formValues[3];

        // Helper to save toggle values
        const saveToggle = async (key, value) => {
            const scoreValue = value ? 1 : 0;
            await player.runCommandAsync(`scoreboard players set "${key}" ${scoreboardName} ${scoreValue}`);
        };

        try {
            await saveToggle(sawhopperKey, sawhopperToggle);
            await saveToggle(lizoredKey, lizoredToggle);
            await saveToggle(spookKey, spookToggle);
            await saveToggle(bubblewingKey, bubblewingToggle);

            player.sendMessage(`§8[§6!§8]§7 Settings were updated!`);
        } catch (err) {
            console.warn("Failed to update one or more toggles:", err);
        }
    }


    static showCraftablesPage(player) {
        const craftablesPage = new ActionFormData()
            .title("§lCRAFTABLES")
            .body(
                "§c§lHow to Craft:§r\n" +
                "To craft items in the §c§lMonsters Add-On §r, you will need to unlock the recipes by getting certain items dropped. If you have the recipe unlocked, you will be able to find it inside the Crafting Table's Recipe Book. To find the item faster, try searching for its name inside the crafting table. \n\n" +
                "If you need info on how to get certain items, you can look inside the pages of each §c§lMonster §rand §c§lBoss§r!"
            )
            .button("Items", "textures/lv/mo/ui/drops.png") // New Button for Items Menu
            .button("Back to Main", "textures/lv/mo/ui/back.png");

        craftablesPage.show(player).then((response) => {
            if (response.canceled) return;

            if (response.selection === 0) {
                this.showItemsMenu(player);
            } else {
                this.showMainMenu(player);
            }
        });
    }

    static showItemsMenu(player) {
        const items = [
            "Balloon",
            "Air Balloon",
            "Basilisk Head",
            "Basilisk Teeth",
            "Bubble Shield",
            "Crab Hat",
            "Grappling Hook",
            "Infinite Water Bucket",
            "Knockback Leg",
            "Lava Loafers",
            "Magma Core",
            "Magma Ingot",
            "Magma Sword",
            "Mimic Flesh",
            "Mimic Trap",
            "Neptune Trident",
            "Neptune Vest",
            "Ocean Tear",
            "Pitchers Shell",
            "Plasma",
            "Plasma Boots",
            "Poison Sword",
            "Prisma Ingot",
            "Sandlurker Claw",
            "Sandlurker Fang",
            "Saw",
            "Saw Blade",
            "Sculk Boots",
            "Sculk Chestplate",
            "Sculk Helmet",
            "Sculk Leggings",
            "Sculk Ingot",
            "Stinger",
            "Void Shard",
            "Void Sword"
        ];

        const itemsMenu = new ActionFormData()
            .title("§lITEMS MENU")
            .body("Select an item to view its details and how to obtain it.");

        items.forEach((item) => {
            itemsMenu.button(item, `textures/lv/mo/items/${item.toLowerCase().replaceAll(" ", "_")}.png`);
        });

        itemsMenu.button("Back to Craftables", "textures/lv/mo/ui/back.png");

        itemsMenu.show(player).then((response) => {
            if (response.canceled || response.selection === items.length) {
                this.showCraftablesPage(player);
            } else {
                const selectedItem = items[response.selection];
                this.showSpecificItem(player, selectedItem);
            }
        });
    }

    static showSpecificItem(player, itemName) {
        const itemData = {
            "Menu": {
                description: "You are viewing the menu right now.",
                howToGet: "Craft it using a stick, leather, and a feather."
            },
            "Balloon": {
                description: "A item that increases your jump height and gives slow falling.",
                howToGet: "Dropped by Balloonagers on mountains."
            },
            "Air Balloon": {
                description: "A rideable hot air balloon.",
                howToGet: "Craftable using Oak Planks, Balloon, and a Emerald."
            },
            "Basilisk Head": {
                description: "A wearable helmet that provides poison resistance.",
                howToGet: "Dropped by Slither in Jungles."
            },
            "Basilisk Teeth": {
                description: "Sharp teeth used as a crafting ingredient for the Poison Sword.",
                howToGet: "Dropped by Slither in Jungles."
            },
            "Bubble Shield": {
                description: "A protective bubble that absorbs damage for a few seconds.",
                howToGet: "Dropped by Bubblewing in Beaches."
            },
            "Crab Hat": {
                description: "A stylish headpiece that grants unlimited fire resistance.",
                howToGet: "Craftable using Pitcher Shells."
            },
            "Grappling Hook": {
                description: "A tool used to latch onto blocks and pull yourself up.",
                howToGet: "Dropped by Gripstone in Dripstone Caves."
            },
            "Infinite Water Bucket": {
                description: "A magical bucket with an infinite water source, will fill up after a few seconds.",
                howToGet: "Crafted using Ocean Tear dropped by Wavebreaker."
            },
            "Knockback Leg": {
                description: "A powerful item that knocks back enemies on impact.",
                howToGet: "Dropped by Bogstrider in Mangroves and Swamps."
            },
            "Lava Loafers": {
                description: "Wearable boots that allow you to walk on lava.",
                howToGet: "Crafted using a Magma Ingot and Netherite Boots."
            },
            "Magma Ingot": {
                description: "A rare ingot used for crafting strong gear.",
                howToGet: "Crafted using materials dropped by Magma King."
            },
            "Magma Sword": {
                description: "A strong sword infused with magma, dealing extra fire damage.",
                howToGet: "Crafted using a Magma Ingot and a Netherite Sword."
            },
            "Mimic Flesh": {
                description: "A strange, fleshy substance dropped by Mimics.",
                howToGet: "Dropped by Mimics in Caves."
            },
            "Mimic Trap": {
                description: "A trap that disguises itself as a chest to troll players.",
                howToGet: "Crafted using Mimic Flesh."
            },
            "Neptune Trident": {
                description: "A powerful melee weapon imbued with lightning energy.",
                howToGet: "Crafted using Prisma Ingots."
            },
            "Neptune Vest": {
                description: "A protective vest that grants water-breathing abilities.",
                howToGet: "Crafted using Prisma Ingots."
            },
            "Ocean Tear": {
                description: "A rare drop that holds the essence of the ocean.",
                howToGet: "Dropped by Wavebreaker in Oceans."
            },
            "Pitchers Shell": {
                description: "Used to craft magma-resistant gear.",
                howToGet: "Dropped by Pitcher in Warped & Crimson Forests."
            },
            "Plasma": {
                description: "A mysterious energy source used for crafting.",
                howToGet: "Dropped by Spook at Night."
            },
            "Plasma Boots": {
                description: "Boots that enhance speed and strength at night.",
                howToGet: "Crafted using Plasma."
            },
            "Poison Sword": {
                description: "A sword that inflicts poison on enemies.",
                howToGet: "Crafted using Basilisk Teeth."
            },
            "Prisma Ingot": {
                description: "A radiant ingot used for crafting oceanic gear.",
                howToGet: "Crafted using materials from Sea Sentry."
            },
            "Sandlurker Claw": {
                description: "A sharp claw that will inflict blindness and slowness.",
                howToGet: "Craftables using Sandlurker Fang."
            },
            "Sandlurker Fang": {
                description: "A fang that can be used to craft.",
                howToGet: "Dropped by Sandlurkers in Deserts."
            },
            "Saw": {
                description: "A tool used for chopping trees instantly. Has a limited amount of uses. §8(Only works in survival!)",
                howToGet: "Crafted using Saw Blade."
            },
            "Saw Blade": {
                description: "A sharp blade used in crafting the Saw.",
                howToGet: "Dropped by Sawhopper in Forest Biomes."
            },
            "Sculk Boots": {
                description: "Strong boots made out of mystical material.",
                howToGet: "Crafted using Sculk Ingot."
            },
            "Sculk Chestplate": {
                description: "Strong chestplate made out of mystical material.",
                howToGet: "Crafted using Sculk Ingot."
            },
            "Sculk Helmet": {
                description: "Strong helmet made out of mystical material.",
                howToGet: "Crafted using Sculk Ingot."
            },
            "Sculk Leggings": {
                description: "Strong leggings made out of mystical material.",
                howToGet: "Crafted using Sculk Ingot."
            },
            "Sculk Ingot": {
                description: "A rare ingot used for crafting sculk gear.",
                howToGet: "Dropped by Sculkosaurus."
            },
            "Stinger": {
                description: "A sharp projectile weapon.",
                howToGet: "Dropped by Buzzer in Warped Forests."
            },
            "Void Shard": {
                description: "A shard infused with the energy of the void.",
                howToGet: "Dropped by Endigrades."
            },
            "Void Handle": {
                description: "A strong impactful handle used to craft the mighty Void Sword.",
                howToGet: "Dropped by The Void."
            },
            "Void Sword": {
                description: "A very powerful Sword with the power of the void. Gives lifesteal and deals damage when standing still.",
                howToGet: "Craftable using the Void Handle and Void Shards."
            }
        };

        const item = itemData[itemName] || {
            description: "Description not available.",
            howToGet: "How to get not available."
        };

        const specificItemMenu = new ActionFormData()
            .title(`§l${itemName}`)
            .body(`§6Description:§r\n${item.description}\n\n§6How To Get:§r\n${item.howToGet}`)
            .button("Back to Items List", "textures/lv/mo/ui/back.png");

        specificItemMenu.show(player).then((response) => {
            if (!response.canceled) {
                this.showItemsMenu(player);
            }
        });
    }

    static showMonstersMenu(player) {
        const monsters = [
            {
                name: "Hoot",
                biomes: ["Pale Garden"],
                description: "This small little owl is attracted to light. Spawning at night, you can lure and tame it using an Open Eyeblossom. Once tamed, you can interact while holding seeds to scan your surroundings for nearby entities. After scanning, the Hoot will need some time to rest afterwards.",
                drops: ["Feather"]
            },
            {
                name: "Sproot",
                biomes: ["Plains"],
                description: "This shy little rock will run away from anyone - unless you have a Poppy. Place it on the fellas head to tame a new friend. Once tamed, you can use a hoe to plant crops on their head.",
                drops: ["Cobblestone", "Grass Block"]
            }, 
            {
                name: "Sculkosaurus Pet",
                biomes: ["None"],
                description: "Hatching from a Sculkosaurus Egg this beast is yours to tame. Using Echo Shards to feed it you can tame and grow the Sculkosaurus Pet, once its fully grown use a saddle to ride it. Jumping while riding will trigger a special attack!",
                drops: ["None"]
            },
            {
                name: "Slither",
                biomes: ["Jungles"],
                description: "At first, it just looks like a rolled-up snake napping in the jungle - until you get too close. Then, this venomous serpent uncoils and starts launching poison projectiles your way. Better watch where you step!",
                drops: ["Basilisk Teeth", "Basilisk Head"]
            },
            {
                name: "Bogstrider",
                biomes: ["Mangroves", "Swamps"],
                description: "With legs longer than a spider jockey's nightmare, this swampy fellow just wants some peace.",
                drops: ["Knockback Leg", "Vine"]
            },
            {
                name: "Sandlurker",
                biomes: ["Mesa Biomes", "Deserts"],
                description: "Don't let the dead bush fool you-get too close, and this creature bursts from the sand.",
                drops: ["Sandlurker Fang", "Deadbush","Gritstone"]
            },
            {
                name: "Snout",
                biomes: ["Taiga Biomes"],
                description: "This chunky boar digs up more farmland than your iron hoe.",
                drops: ["Leather", "Porkchop", "Variety of Seeds"]
            },
            {
                name: "Sawhopper",
                biomes: ["Forest Biomes"],
                description: "A grasshopper with a face like a sawblade-because Minecraft needs more weirdness!",
                drops: ["Random Logs", "Saw Blade"]
            },
            {
                name: "Mimic",
                biomes: ["Dungeons"],
                description: "See a chest in a cave? Don't trust it! It's a Mimic with hops.",
                drops: ["Mimic Flesh", "Oak Planks"]
            },
            {
                name: "Lizored",
                biomes: ["Dripstone Caves"],
                description: "This ore-covered lizard snacks on dripstone like you snack on golden carrots. Once it has eaten some dripstone try using a shear to harvest its ores.",
                drops: ["Dripstone Block"]
            },
            {
                name: "Torch Golem",
                biomes: ["Caves"],
                description: "One second you're lighting up a cave, the next-bam! Total darkness.",
                drops: ["String", "Honeycomb"]
            },
            {
                name: "Gripstone",
                biomes: ["Dripstone Caves"],
                description: "Looks like harmless dripstone, but walk underneath and this thing snatches you.",
                drops: ["Grappling Hook", "Pointed Dripstone"]
            },
            {
                name: "Wavebreaker",
                biomes: ["Oceans"],
                description: "This fast surfer hates boats-probably because they get in its way!",
                drops: ["Ocean's Tear"]
            },
            {
                name: "Balloonager",
                biomes: ["Mountains"],
                description: "This hot air balloon scout from the pillagers is always searching for something-maybe trouble, maybe treasure.",
                drops: ["Balloon", "Crossbow", "Variety of food", "Pillager Outpost loot"]
            },
            {
                name: "Bubblewing",
                biomes: ["Beaches"],
                description: "Part manta ray, part dragonfly, and full of bubbles.",
                drops: ["Bubble Shield", "Rarerly Diamond"]
            },
            {
                name: "Pitcher",
                biomes: ["Warped & Crimson Forest"],
                description: "Crab from the Nether who's mastered the art of flinging players across lava pools.",
                drops: ["Pitcher's Shell"]
            },
            {
                name: "Buzzer",
                biomes: ["Warped Forest Biomes"],
                description: "These angry little pests swarm and sting with poison.",
                drops: ["Stinger"]
            },
            {
                name: "Endigrade",
                biomes: ["End"],
                description: "This slow-floating creature may seem harmless, but its blasts blind you and send you flying.",
                drops: ["Void Shards"]
            },
            {
                name: "Spook Cow",
                biomes: ["Night"],
                description: "This ghostly cow lurks in the night, seeking revenge for all the cows you've killed.",
                drops: ["Plasma", "Rotten Flesh", "Leather"]
            },
            {
                name: "Spook Pig",
                biomes: ["Night"],
                description: "This spectral pig haunts the night, avenging fallen pigs.",
                drops: ["Plasma", "Rotten Flesh"]
            },
            {
                name: "Spook Chicken",
                biomes: ["Night"],
                description: "This eerie chicken appears at night to scare players who have harmed chickens.",
                drops: ["Plasma", "Rotten Flesh", "Feathers"]
            },
            {
                name: "Spook Sheep",
                biomes: ["Night"],
                description: "A phantom sheep haunting the night, protecting the memory of all the sheared sheep.",
                drops: ["Plasma", "Wool", "Rotten Flesh"]
            }
        ];

        const monstersMenu = new ActionFormData()
            .title("§lMONSTERS MENU")
            .body("§rSelect a monster to explore its details, biomes, and drops.");

        monsters.forEach((monster) => {
            monstersMenu.button(monster.name, `textures/lv/mo/ui/${monster.name.toLowerCase().replaceAll(" ", "_")}.png`);
        });

        monstersMenu.button("Back to Main", "textures/lv/mo/ui/back.png");

        monstersMenu.show(player).then((response) => {
            if (response.canceled || response.selection === monsters.length) {
                this.showMainMenu(player);
            } else {
                const selectedMonster = monsters[response.selection];
                this.showSpecificMonster(player, selectedMonster);
            }
        });
    }

    static showSpecificMonster(player, monster) {
        const specificMonsterMenu = new ActionFormData()
            .title(`§l${monster.name}`)
            .body(
                `§6Description:\n§r${monster.description}\n\n` +
                `§6Biomes:\n§r${monster.biomes.join(", ")}\n\n` +
                `§6Drops:\n§r${monster.drops.map((drop) => `- ${drop}`).join("\n")}`
            )
            .button("Back to Monsters List", "textures/lv/mo/ui/back.png");

        specificMonsterMenu.show(player).then((response) => {
            if (!response.canceled) {
                this.showMonstersMenu(player);
            }
        });
    }

    static showBossesMenu(player) {
        const bosses = [
            {
                name: "Sculkosaurus",
                summon: "The Sculkosaurus can be found in the naturally spawning structure deep underground.",
                description: "Even the Warden hides when this guy shows up! This boss blasts explosive Sonic Beams.",
                drops: ["Echo Shards", "Sculk Ingots", "Sculkosaurus Egg", "Experience Bottles", "Sculkosaurus Trophy"]
            },
            {
                name: "Sea Sentry",
                summon: "The Sea Sentry can be found in the naturally spawning structure found in the ocean.",
                description: "This glowing guardian of the deep packs a punch with melee strikes and water waves.",
                drops: ["Prismarine Shard", "Prisma Ingot", "Experience Bottles", "Heart Of The Sea", "Sea Sentry Trophy"]
            },
            {
                name: "Magma King",
                summon: "The Magma King can be found in the naturally spawning structure in the Nether.",
                description: "Rising from the lava, this fiery ruler sends waves of molten destruction your way.",
                drops: ["Magma Ingots", "Variety of bastion loot", "Magma King Trophy"]
            },
            {
                name: "The Void",
                summon: "The Void can be found in the naturally spawning structure in the End.",
                description: "The ultimate boss of the End.",
                drops: ["Void Handle", "Experience Bottles", "The Void Trophy"]
            }
        ];

        const bossesMenu = new ActionFormData()
            .title("§lBOSSES MENU")
            .body("Select a boss to explore its details, how to summon it, and its drops.");

        bosses.forEach((boss) => {
            bossesMenu.button(boss.name, `textures/lv/mo/ui/${boss.name.toLowerCase().replace(" ", "_")}.png`);
        });

        bossesMenu.button("Back to Main", "textures/lv/mo/ui/back.png");

        bossesMenu.show(player).then((response) => {
            if (response.canceled || response.selection === bosses.length) {
                this.showMainMenu(player);
            } else {
                const selectedBoss = bosses[response.selection];
                this.showSpecificBoss(player, selectedBoss);
            }
        });
    }

    static showSpecificBoss(player, boss) {
        const specificMenu = new ActionFormData()
            .title(`§l${boss.name}`)
            .body(
                `§6Description:\n§r${boss.description}\n\n` +
                `§6How To Summon:\n§r${boss.summon}\n\n` +
                `§6Drops:\n§r${boss.drops.map((drop) => `- ${drop}`).join("\n")}`
            )
            .button("Back to Boss List", "textures/lv/mo/ui/back.png");

        specificMenu.show(player).then((response) => {
            if (!response.canceled) {
                this.showBossesMenu(player);
            }
        });
    }
}

// Export the class
export default MonsterAndBossGuide;
