// Import necessary modules from Minecraft server API
import { world, ItemStack, BlockPermutation } from "@minecraft/server";

const pinkPetalsLikeBlocks = ["hb_hr:mushroom_litter"];

export const pinkPetalsLikeBlockComponent = {
  onTick({ block }) {
    if (!pinkPetalsLikeBlocks.includes(block.typeId)) return;
    if (block.permutation.getState("hb_hr:placed_bit") == true) return;
    const randomVariant = Math.floor(Math.random() * 3);

    const baseStates = {
      "hb_hr:placed_bit": true,
      "hb_hr:growth": randomVariant,
      "hb_hr:rotation": Math.floor(Math.random() * 3),
    };
    const newPerm = BlockPermutation.resolve(block.typeId, baseStates);
    block.setPermutation(newPerm);
  },
  beforeOnPlayerPlace(e) {
    const { permutationToPlace, block } = e;

    const baseStates = {
      "hb_hr:placed_bit": true,
      "hb_hr:growth": 0,
      "hb_hr:rotation": Math.floor(Math.random() * 3),
    };

    const newPerm = BlockPermutation.resolve(permutationToPlace.type.id, baseStates);

    e.permutationToPlace = newPerm;
  },
  onPlayerInteract(e) {
    // Destructure event data for easier access
    const { block, player } = e;

    // Get the block's current location
    const { x, y, z } = block.location;

    // Get the equipment component for the player
    const equipment = player.getComponent("equippable");
    // Get the selected item from the player's mainhand
    const selectedItem = equipment.getEquipment("Mainhand");

    // Check if the selected item is 'hb_hr:mushroom_litter' or 'minecraft:bone_meal'
    if (selectedItem && (selectedItem.typeId === "hb_hr:mushroom_litter" || selectedItem.typeId === "minecraft:bone_meal")) {
      // Get the current permutation of the block
      const permutation = block.permutation;

      // Get the current hb_hr:growth state value
      const currentGrowthLevel = permutation.getState("hb_hr:growth");

      // If the selected item is 'minecraft:bone_meal' and growth level is 3, spawn particle and spawn a hb_hr:mushroom_litter
      if (selectedItem.typeId === "minecraft:bone_meal" && currentGrowthLevel === 3) {
        block.dimension.spawnParticle("minecraft:crop_growth_emitter", { x: x + 0.5, y: y + 0.5, z: z + 0.5 });
        const pinkPetalsItem = new ItemStack("hb_hr:mushroom_litter", 1);
        block.dimension.spawnItem(pinkPetalsItem, { x: x + 0.5, y: y + 0.5, z: z + 0.5 });

        // Reduce bone meal from player's inventory
        if (player.getGameMode() !== "creative") {
          if (selectedItem.amount > 1) {
            selectedItem.amount -= 1;
            equipment.setEquipment("Mainhand", selectedItem);
          } else {
            equipment.setEquipment("Mainhand", undefined); // Clear the slot if only 1 item left
          }
        }

        // Prevent further execution
        e.cancel = true;
      }

      // Check if the growth level is less than or equal to 2
      else if (currentGrowthLevel <= 2) {
        // Prevent default block placement behavior
        e.cancel = true;

        // Increase the hb_hr:layer_level state by 1
        const newGrowthLevel = currentGrowthLevel + 1;

        const baseStates = {
          "hb_hr:placed_bit": true,
          "hb_hr:growth": newGrowthLevel,
          "hb_hr:rotation": permutation.getState("hb_hr:rotation"),
        };

        const newPerm = BlockPermutation.resolve(block.typeId, baseStates);

        // block.setPermutation(newPerm);
        // Set the block's permutation to the new permutation
        block.setPermutation(newPerm);

        // If the selected item is 'minecraft:bone_meal', spawn 'minecraft:crop_growth_emitter' particle
        if (selectedItem.typeId === "minecraft:bone_meal") {
          block.dimension.spawnParticle("minecraft:crop_growth_emitter", { x: x + 0.5, y: y + 0.5, z: z + 0.5 });
        }

        // Reduce one 'hb_hr:mushroom_litter' item from the player's inventory if not in creative mode
        if (player.getGameMode() !== "creative") {
          if (selectedItem.amount > 1) {
            selectedItem.amount -= 1;
            equipment.setEquipment("Mainhand", selectedItem);
          } else {
            equipment.setEquipment("Mainhand", undefined); // Clear the slot if only 1 item left
          }
        }
      }
    }
  },
  onPlayerDestroy(e) {
    // Destructure event data for easier access
    const { dimension, block } = e;

    // Extract destroyed block permutation from event data
    const { destroyedBlockPermutation: perm } = e;

    // Get the hb_hr:growth state of the destroyed block
    const growthLevel = perm.getState("hb_hr:growth");

    // Determine the number of pink petals items to spawn based on the hb_hr:growth block state value
    let dropCount = 0;
    if (growthLevel === 0) {
      dropCount = 1;
    } else if (growthLevel === 1) {
      dropCount = 2;
    } else if (growthLevel === 2) {
      dropCount = 3;
    } else if (growthLevel === 3) {
      dropCount = 4;
    }

    // Spawn the pink petals items at the destroyed block location if any should be spawned
    if (dropCount > 0) {
      const pinkPetalsItem = new ItemStack("hb_hr:mushroom_litter", dropCount);
      dimension.spawnItem(pinkPetalsItem, block.location);
    }
  },
};

const customComponents = {
  "hb_hr:pink_petals_like_block": pinkPetalsLikeBlockComponent,
};

export function pinkPetalsBlock() {
  world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    for (const [componentName, componentImplementation] of Object.entries(customComponents)) {
      blockComponentRegistry.registerCustomComponent(componentName, componentImplementation);
    }
  });
}
