import { BlockPermutation, EquipmentSlot, TimeOfDay, system, world, ItemStack, StructureAnimationMode, StructureRotation, StructureSaveMode } from "@minecraft/server";
import { checkBelowEntityDespawn, getStringBefore, checkLocation, getEntityRotation, getLocationbyFacingBlock, stringBetween, getGamemode, getElementPosition, getElementPositionArrayWithObjects } from "./helpers";
import { cameraCutscene } from "../events/camera";
import { ActionFormData } from "@minecraft/server-ui";

// Custom component implementation for bench interaction and placement
const fireFlyJarHandlerBlockComponent = {
  // Called when a player interacts with the bench block
  onTick(e) {
    const { block, dimension } = e; // Destructure the event to get block and player
    let nearbyEntities = world.getDimension(block.dimension.id).getEntities({
      type: "hb_cb:fireflies",
      location: { x: block.center().x, y: block.y, z: block.center().z },
      minDistance: 0,
      maxDistance: 0.2,
    });
    if (!block.permutation.getState("hb_cb:has_fireflies")) {
      if (!nearbyEntities[0]) return;
      nearbyEntities[0].remove();
      return;
    }
    if (!nearbyEntities[0]) {
      dimension.spawnEntity("hb_cb:fireflies", { x: block.center().x, y: block.y, z: block.center().z });
    }

    return;
  },
  // Called when a player interacts with the bench block
  onPlayerInteract(e) {
    const { block, player } = e; // Destructure the event to get block and player
  },
};

// Register custom components to use in world initialization
const customComponents = {
  "hb_cb:firefly_jar_handler": fireFlyJarHandlerBlockComponent,
};

// add block componetn and BlockComponentPlayerPlace for cancel of block when interacting with firefly bush

export class fireflyJarHandler {
  static initialized = false;
  constructor() {
    this.initialize();
  }

  initialize() {
    if (!fireflyJarHandler.initialized) {
      fireflyJarHandler.initialized = true;
      this.processSubscriptions();
    } else {
    }
  }
  processSubscriptions() {
    let curTick = 0;
    const INIT_TIME = 0;

    system.runInterval(() => {
      try {
        if (curTick > INIT_TIME) {
          const allPlayers = world.getAllPlayers();
          allPlayers.forEach((player) => {
            if (!player.isValid()) return;
            else {
              checkBelowEntityDespawn(player, "fire");
            }
          });
        }
        curTick++;
      } catch (e) {
        console.warn(e);
      }
    }, 0);
    // Register our custom block components when the world initializes
    world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
      for (const [componentName, componentImplementation] of Object.entries(customComponents)) {
        blockComponentRegistry.registerCustomComponent(componentName, componentImplementation);
      }
    });

    world.afterEvents.playerBreakBlock.subscribe((event) => {
      const block = event.block;
      const blockPerm = event.brokenBlockPermutation;
      const usedItem = event.itemStackAfterBreak;
      const player = event.player;
      if (blockPerm.type.id == "hb_cb:firefly_jar_block") {
        let gamemodeCreative = getGamemode(player, 1);
        if (gamemodeCreative) return;
        system.run(() => {
          let nearbyEntities = world.getDimension(block.dimension.id).getEntities({
            type: "hb_cb:fireflies",
            location: { x: block.center().x, y: block.y, z: block.center().z },
            minDistance: 0,
            maxDistance: 0.2,
          });
          if (nearbyEntities[0]) nearbyEntities[0].remove();
          let newItem = new ItemStack("hb_cb:firefly_jar_block");
          if (blockPerm.getState("hb_cb:has_fireflies")) {
            // world.sendMessage("this?");
            newItem.setDynamicProperty("hb_cb:has_fireflies", 1);
            newItem.setLore(["§6Fireflies inside"]);
          }
          block.dimension.spawnItem(newItem, block.location);
        });
      }
    });

    world.afterEvents.playerInteractWithBlock.subscribe((event) => {
      const item = event.itemStack;
      const player = event.player;
      const block = event.block;
      const typeId = player.typeId;
      if (typeId !== "minecraft:player") {
        return;
      }
      if (!item) return;
      if (block.typeId != "minecraft:firefly_bush" && item.typeId != "hb_cb:firefly_jar_block") return;
      const hasFireflies = item.getDynamicProperty("hb_cb:has_fireflies") ?? 0;
      if (hasFireflies || player.getGameMode() === "creative") return;
      if (block.typeId == "hb_cb:firefly_jar_block" && item.typeId == "hb_cb:firefly_jar_block" && !hasFireflies) return;

      item.setDynamicProperty("hb_cb:has_fireflies", 1);

      item.setLore(["§6Fireflies inside"]);

      const equippable = player.getComponent("equippable");
      const slot = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
      if (!equippable || !slot) return;
      slot.setItem(item);
    });
    world.beforeEvents.itemUseOn.subscribe((event) => {
      const player = event.source;
      const item = event.itemStack;
      const block = event.block;
      const face = event.blockFace;
      if (item.typeId == "hb_cb:firefly_jar_block" && block.typeId == "minecraft:firefly_bush") {
        event.cancel = true;
        system.run(() => {
          // block.dimension.spawnEntity("hb_cb:fireflies", { x: block.center().x, y: block.y, z: block.center().z });
          const hasFireflies = item.getDynamicProperty("hb_cb:has_fireflies") ?? 0;
          if (hasFireflies) return;
          // world.sendMessage("ADD FIREFLIOES TO ITEM");
          item.setDynamicProperty("hb_cb:has_fireflies", 1);

          item.setLore(["§6Fireflies inside"]);

          const equippable = player.getComponent("equippable");
          const slot = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
          if (!equippable || !slot) return;
          slot.setItem(item);
          return;
        });
      }
      if (item.typeId == "hb_cb:firefly_jar_block" && block.typeId != "minecraft:firefly_bush" && block.typeId == "hb_cb:firefly_jar_block") {
        // world.sendMessage("edit jar");
        let fireFlyTag = false;

        system.run(() => {
          // world.sendMessage("err1");
          const hasFireflies = item.getDynamicProperty("hb_cb:has_fireflies") ?? 0;
          if (!hasFireflies || player.getGameMode() === "creative") return;
          // world.sendMessage("REMOVE FIREFLIOES TO ITEM");
          fireFlyTag = true;
          item.setDynamicProperty("hb_cb:has_fireflies", 0);

          item.setLore([]);

          const equippable = player.getComponent("equippable");
          const slot = equippable.getEquipmentSlot(EquipmentSlot.Mainhand);
          if (!equippable || !slot) return;
          slot.setItem(item);
        });

        system.runTimeout(() => {
          // world.sendMessage("above: " + block.typeId);
          if (block.typeId == "hb_cb:firefly_jar_block") {
            if (!fireFlyTag) return;
            // world.sendMessage("edit here");
            const baseStates = {
              "hb_cb:has_fireflies": true,
            };
            block.dimension.spawnEntity("hb_cb:fireflies", { x: block.center().x, y: block.y, z: block.center().z });
            if (!block || block.typeId != "hb_cb:firefly_jar_block") return;
            const newPerm = BlockPermutation.resolve(block.typeId, baseStates);
            block.setPermutation(newPerm);
          }
        }, 1);
        return;
      }
      if (item.typeId == "hb_cb:firefly_jar_block" && block.typeId != "minecraft:firefly_bush" && block.typeId != "hb_cb:firefly_jar_block") {
        const hasFireflies = item.getDynamicProperty("hb_cb:has_fireflies") ?? 0;
        if (!hasFireflies) return;
        if (hasFireflies) {
          system.runTimeout(() => {
            if (block.above().typeId == "hb_cb:firefly_jar_block") {
              const baseStates = {
                "hb_cb:has_fireflies": true,
              };
              block.dimension.spawnEntity("hb_cb:fireflies", { x: block.above().center().x, y: block.above().y, z: block.above().center().z });
              if (!block.above() || block.above().typeId != "hb_cb:firefly_jar_block") return;
              const newPerm = BlockPermutation.resolve(block.above().typeId, baseStates);
              block.above().setPermutation(newPerm);
            }
          }, 1);
          // world.sendMessage("add fireflies");
        }
        // world.sendMessage("place jar");
      }
    });
  }
}
