import { EnchantmentTypes, EquipmentSlot, ItemStack, world } from "@minecraft/server";
import { beforeEvents, namespace as ns } from "./eternal/constants";
import { dropEntity, catchEntity, storeBugData, getBugData } from "./bugNet";
import { runTimeout } from "./eternal/utils";

const variations = ["blue", "nightsky", "orange", "pearl", "striped", "yellow", "yellowtailed"];

const glassJarComponent = {
  onPlayerInteract(e) {
    const { player, block, dimension } = e;

    const item = player.getEquipment(EquipmentSlot.Mainhand);
    if (item && item.typeId.startsWith(`${ns}:bug_net.`)) {
      const v = item.typeId.split(".")[1];
      const displayEntity = dimension.getEntities({ families: ["glass_jar_display"], location: block.center, maxDistance: 1 })[0];
      if (v === "full") {
        if (displayEntity) return;

        let id = item.getDynamicProperty(`${ns}:typeId`);
        if (!id.includes("glass_jar")) {
          const ent = id.split(":")[1];
          id = `${ns}:glass_jar.${ent}`;
        }
        dimension.playSound("ecbl_bc.random.glass_jar.open", block.center);
        dropEntity(player, id, dimension, block.bottomCenter);
      } else if (v === "empty") {
        if (!displayEntity) return;

        const ent = displayEntity.typeId.split(".")[1];
        const entity = dimension.spawnEntity(`${ns}:${ent}`, block.center);
        entity.addEffect("invisibility", 2, { showParticles: false });

        if (ent !== "firefly") {
          try {
            copyBugData(displayEntity, entity);
          } catch (error) {
            console.error("Erro ao copiar dados do bug:", error);
          }
        }

        displayEntity.dispose();

        runTimeout(() => {
          dimension.playSound("ecbl_bc.random.glass_jar.close", block.center);
          catchEntity(player, entity, item);
        }, 1);
      }
    }
  },
  onPlayerDestroy(e) {
    const { block, dimension, player } = e;

    const item = player.getEquipment(EquipmentSlot.Mainhand);
    const itemEntity = dimension.getEntities({ type: "minecraft:item", location: block.center, maxDistance: 1 })[0];
    const gjEntity = dimension.getEntities({ families: ["glass_jar_display"], location: block.center, maxDistance: 1 })[0];
    let displayType = gjEntity?.typeId.split(".")[1];

    if (item && item.hasEnchantment("silk_touch")) {
      if (gjEntity) {
        itemEntity?.dispose();

        if (displayType === "butterfly") {
          displayType += `_${variations[gjEntity.getProperty(`${ns}:variant`)]}`;
        }

        const jarItem = new ItemStack(`${ns}:glass_jar_${displayType}`);

        storeBugData(jarItem, gjEntity);
        gjEntity.dispose();

        dimension.spawnItem(jarItem, block.center);
      }
    } else {
      itemEntity?.dispose();

      if (gjEntity) {
        const entity = dimension.spawnEntity(`${ns}:${displayType}`, block.bottomCenter);

        if (displayType !== "firefly") {
          try {
            copyBugData(gjEntity, entity);
          } catch (error) {
            console.error("Erro ao copiar dados do bug:", error);
          }
        }

        gjEntity.dispose();
      }
    }
  },
  beforeOnPlayerPlace(e) {
    const { player, dimension, block } = e;
    const item = player.getEquipment(EquipmentSlot.Mainhand);
    const match = item.typeId.match(/glass_jar_([^_]+)/);
    if (match) {
      const entity = dimension.spawnEntity(`${ns}:glass_jar.${match[1]}`, block.bottomCenter);
      if (item.getDynamicPropertyTotalByteCount()) {
        getBugData(entity, item);
      } else {
        const variant = item.typeId.split(`butterfly_`)[1];
        if (variant) {
          const i = variations.indexOf(variant);
          entity.setProperty(`${ns}:variant`, i);
        }
      }
    }
  },
  onTick(e) {
    const { block, dimension } = e;
    const entity = dimension.getEntities({ families: ["glass_jar_display"], type: `${ns}:glass_jar.firefly`, location: block.center, maxDistance: 1 })[0];

    if (entity) {
      block.setState("p:is_light_emitting", true);
    } else {
      block.setState("p:is_light_emitting", false);
    }
  },
};

function copyBugData(fromEntity, toEntity) {
  if (fromEntity && toEntity) {
    if (fromEntity.nameTag !== undefined) {
      toEntity.nameTag = fromEntity.nameTag;
    }

    if (fromEntity.health !== undefined) {
      toEntity.health = fromEntity.health;
    }

    const variant = fromEntity.getProperty(`${ns}:variant`);
    if (variant !== undefined && variant !== null) {
      toEntity.setProperty(`${ns}:variant`, variant);
    }
  } else {
    console.error("Erro ao copiar dados: uma ou ambas as entidades são indefinidas.");
  }
}

beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
  blockComponentRegistry.registerCustomComponent(`${ns}:glass_jar`, glassJarComponent);
});
