import { world, system, BlockPermutation, ItemStack } from "@minecraft/server"
import { ModalFormData } from "@minecraft/server-ui"


export class AutoComposterComponent {
    constructor() {
        this.onTick = this.onTick.bind(this);
        this.onPlayerInteract = this.onPlayerInteract.bind(this);

        this.VALID_ITEMS = [
            "minecraft:stick",
            "minecraft:resin_clump",
            "minecraft:resin_brick",
            "minecraft:honeycomb",
            "minecraft:sea_pickle",
            "minecraft:bamboo",
            "minecraft:spore_blossom",
            "minecraft:cactus",
            "minecraft:sculk_vein",
            "minecraft:sculk",
            "minecraft:string",
            "minecraft:armadillo_scute",
            "minecraft:waterlily",
            "minecraft:feather",
            "minecraft:wither_rose",
            "minecraft:glow_lichen",
            "minecraft:mangrove_propagule",
            "minecraft:rotten_flesh",
            "minecraft:spider_eye",
            "minecraft:fermented_spider_eye",
            "minecraft:bone",
            "minecraft:web",
            "minecraft:turtle_scute",
            "minecraft:gunpowder",
            "minecraft:closed_eyeblossom",
            "minecraft:open_eyeblossom",
            "minecraft:pitcher_plant",
            "minecraft:pitcher_pod",
            "minecraft:sugar_cane",
            "minecraft:wheat",
            "minecraft:beetroot",
            "minecraft:nautilus_shell",
            "minecraft:phantom_membrane",
            "minecraft:carrot",
            "minecraft:apple",
            "minecraft:egg",
            "minecraft:sugar",
            "minecraft:nether_sprouts",
            "minecraft:poppy",
            "minecraft:dandelion",
            "minecraft:blue_orchid",
            "minecraft:allium",
            "minecraft:azure_bluet",
            "minecraft:oxeye_daisy",
            "minecraft:cornflower",
            "minecraft:lily_of_the_valley",
            "minecraft:rose_bush",
            "minecraft:pink_petals",
            "minecraft:sunflower",
            "minecraft:lilac",
            "minecraft:peony",
            "minecraft:bone_meal",
            "minecraft:cocoa_beans",
            "minecraft:torchflower",
            "minecraft:nether_wart",
            "minecraft:cake",
            "minecraft:bread",
            "minecraft:cookie",
            "minecraft:shulker_shell",
            "minecraft:blaze_rod",
            "minecraft:breeze_rod",
            "minecraft:magma_cream",
            "minecraft:paper",
            "minecraft:ender_pearl",
            "minecraft:slime_ball",
            "minecraft:leather",
            "minecraft:ghast_tear",
            "minecraft:blaze_powder",

        ]
    }

    onPlayerInteract(e) {
        const block = e.block;

        const player = e.player;
        let selectedSlot = player.selectedSlotIndex;
        let handItem = player.getComponent("inventory").container.getItem(selectedSlot);

        if (handItem) {
            if (handItem.typeId == "pb_red:redstone_wrench") {
                const AllStates = [
                    { state: "minecraft:cardinal_direction", values: ["north", "east", "south", "west"] },
                    { state: "minecraft:facing_direction", values: ["north", "east", "south", "west", "up", "down"] }
                ]

                AllStates.some((stateObj) => {
                    const currentState = block.permutation.getState(stateObj.state);

                    if (currentState !== undefined && currentState !== null) {
                        const stateValues = stateObj.values;
                        const currentStateIndex = stateValues.indexOf(currentState);
                        const nextState = currentStateIndex >= stateValues.length - 1 ? stateValues[0] : stateValues[currentStateIndex + 1];

                        block.setPermutation(block.permutation.withState(stateObj.state, nextState));
                        block.dimension.runCommand(`playsound vr.stutterturn @a ${block.location.x} ${block.location.y} ${block.location.z}`)
                    }
                });
            }
        }
    }

    getFrontandBack(direction, block) {
        let frontBlock, backBlock;
        switch (direction) {
            case 'north':
                frontBlock = block.north();
                backBlock = block.south();
                break;
            case 'south':
                frontBlock = block.south();
                backBlock = block.north();
                break;
            case 'east':
                frontBlock = block.east();
                backBlock = block.west();
                break;
            case 'west':
                frontBlock = block.west();
                backBlock = block.east();
                break;
        }
        return { frontBlock, backBlock };
    }

    isValidContainer(block) {
        if (!block) return;
        const validContainers = [
            "minecraft:chest",
            "minecraft:hopper",
            "minecraft:barrel",
            "minecraft:dropper",
            "minecraft:dispenser",
            "minecraft:trapped_chest",
            //shulker box
            "minecraft:undyed_shulker_box",
            "minecraft:black_shulker_box",
            "minecraft:blue_shulker_box",
            "minecraft:brown_shulker_box",
            "minecraft:cyan_shulker_box",
            "minecraft:gray_shulker_box",
            "minecraft:green_shulker_box",
            "minecraft:light_blue_shulker_box",
            "minecraft:light_gray_shulker_box",
            "minecraft:lime_shulker_box",
            "minecraft:magenta_shulker_box",
            "minecraft:orange_shulker_box",
            "minecraft:pink_shulker_box",
            "minecraft:purple_shulker_box",
            "minecraft:red_shulker_box",
            "minecraft:white_shulker_box",
            "minecraft:yellow_shulker_box",


        ];
        return validContainers.includes(block.typeId);
    }

    isCompostable(id) {
        if (this.VALID_ITEMS.includes(id)) return true

        if (id.includes("leaves")) return true
        if (id.includes("vine")) return true
        if (id.includes("azalea")) return true
        if (id.includes("moss")) return true
        if (id.includes("fern")) return true
        if (id.includes("dripleaf")) return true
        if (id.includes("melon")) return true
        if (id.includes("pumpkin")) return true
        if (id.includes("roots")) return true
        if (id.includes("grass")) return true
        if (id.includes("berries")) return true
        if (id.includes("fungus")) return true
        if (id.includes("mushroom")) return true
        if (id.includes("chorus")) return true
        if (id.includes("kelp")) return true
        if (id.includes("potato")) return true
        if (id.includes("sapling")) return true
        if (id.includes("seeds")) return true
        if (id.includes("coral")) return true
        if (id.includes("dye")) return true
        if (id.includes("bush")) return true
        if (id.includes("tulip")) return true
        if (id.includes("ink")) return true
        if (id.includes("stew")) return true
        if (id.includes("soup")) return true
        if (id.includes("porkchop")) return true
        if (id.includes("chicken")) return true
        if (id.includes("beef")) return true
        if (id.includes("mutton")) return true
        if (id.includes("rabbit")) return true
        if (id.includes("fish")) return true
        if (id.includes("cod")) return true
        if (id.includes("salmon")) return true
        if (id.includes("wool")) return true

    }

    onTick(e) {
        const { block } = e;
        let direction = block.permutation.getState('minecraft:cardinal_direction');
        const chest = block.above();
        const { frontBlock, backBlock } = this.getFrontandBack(direction, block);
        if (!chest || !backBlock) return

        if (!this.isValidContainer(chest)) return;

        let inventory = chest.getComponent("minecraft:inventory")?.container;
        if (!inventory) return;

        const compostLevel = block.permutation.getState("pb_red:compost_level");
        let currentCompost = compostLevel;
        let totalBoneMealToDrop = 0;

        for (let slot = 0; slot < inventory.size; slot++) {
            let chestItem = inventory.getItem(slot);
            if (!chestItem || !this.isCompostable(chestItem.typeId)) continue;

            if (chestItem.amount >= 10) {
                const itemsToProcess = Math.floor(chestItem.amount / 10);
                const leftoverItems = chestItem.amount % 10;

                totalBoneMealToDrop += itemsToProcess;

                currentCompost += leftoverItems;

                while (currentCompost >= 10) {
                    totalBoneMealToDrop += 1;
                    currentCompost -= 10;
                }

                inventory.setItem(slot, new ItemStack("minecraft:air", 1));
                break;
            }

            if (currentCompost < 10) {
                currentCompost += chestItem.amount;

                while (currentCompost >= 10) {
                    totalBoneMealToDrop += 1;
                    currentCompost -= 10;
                }

                inventory.setItem(slot, new ItemStack("minecraft:air", 1));
                break;
            }
        }

        if (totalBoneMealToDrop > 0) {
            const stacksToDrop = Math.ceil(totalBoneMealToDrop / 64);
            let remainingBoneMeals = totalBoneMealToDrop;

            for (let i = 0; i < stacksToDrop; i++) {
                const dropAmount = Math.min(remainingBoneMeals, 64);
                block.dimension.spawnItem(
                    new ItemStack("minecraft:bone_meal", dropAmount),
                    {
                        x: backBlock.location.x + 0.5,
                        y: backBlock.location.y + 0.2,
                        z: backBlock.location.z + 0.5,
                    }
                ).teleport({
                    x: backBlock.location.x + 0.5,
                    y: backBlock.location.y - 0.2,
                    z: backBlock.location.z + 0.5,
                });
                block.dimension.runCommand(`playsound random.pop @a ${block.location.x} ${block.location.y} ${block.location.z} 0.5`)

                remainingBoneMeals -= dropAmount;
            }
        }

        block.setPermutation(block.permutation.withState("pb_red:compost_level", currentCompost));
    }


}
