import {
  world,
  system,
  EntityComponentTypes,
  EquipmentSlot,
  ItemStack,
} from "@minecraft/server";
import {
  getBuddyPartIndex,
  buddyHeads,
  buddyTorsos,
  buddyLegs,
  checkBuddyProperties,
  getBuddyFoodIndex,
} from "./getBuddyPart";

import { randomBuddyName } from "./getBuddyName";

world.beforeEvents.playerInteractWithEntity.subscribe((data) => {
  const player = data.player;
  const buddy = data.target;

  const equippedItem = player.getComponent(EntityComponentTypes.Equippable);
  const slotMainHand = equippedItem.getEquipment(EquipmentSlot.Mainhand);

  if (buddy.typeId == "arcedge_bap:buddy_trader" && player.isSneaking) {
    data.cancel = true;
    system.run(() => {
      buddy.triggerEvent("arcedge_bap:despawn_buddy_trader");
    });
  }

  if (buddy.typeId == "arcedge_bap:buddy_builder") {
    const buddyPartMatch = getBuddyPartIndex(slotMainHand?.typeId);

    if (!buddyPartMatch) return;

    system.run(() => {
      equippedItem.setEquipment(EquipmentSlot.Mainhand, undefined);

      const dropItem = (itemId) => {
        const stack = new ItemStack(itemId, 1);
        player.dimension.spawnItem(stack, buddy.location);
      };

      if (
        buddyPartMatch.type == "head" &&
        buddy.getProperty("arcedge_bap:head_part") > 0
      )
        dropItem(buddyHeads[buddy.getProperty("arcedge_bap:head_part") - 1]);
      if (
        buddyPartMatch.type == "torso" &&
        buddy.getProperty("arcedge_bap:torso_part") > 0
      )
        dropItem(buddyTorsos[buddy.getProperty("arcedge_bap:torso_part") - 1]);
      if (
        buddyPartMatch.type == "legs" &&
        buddy.getProperty("arcedge_bap:legs_part") > 0
      )
        dropItem(buddyLegs[buddy.getProperty("arcedge_bap:legs_part") - 1]);
      switch (buddyPartMatch.type) {
        case "head":
          buddy.setProperty("arcedge_bap:head_part", buddyPartMatch.index + 1);
          break;
        case "torso":
          buddy.setProperty("arcedge_bap:torso_part", buddyPartMatch.index + 1);
          break;
        case "legs":
          buddy.setProperty("arcedge_bap:legs_part", buddyPartMatch.index + 1);
          break;
      }

      let partsCollected = 1;
      if (
        buddy.getProperty("arcedge_bap:head_part") > 0 &&
        partsCollected < 3 &&
        buddyPartMatch.type != "head"
      )
        partsCollected = partsCollected + 1;
      if (
        buddy.getProperty("arcedge_bap:torso_part") > 0 &&
        partsCollected < 3 &&
        buddyPartMatch.type != "torso"
      )
        partsCollected = partsCollected + 1;
      if (
        buddy.getProperty("arcedge_bap:legs_part") > 0 &&
        partsCollected < 3 &&
        buddyPartMatch.type != "legs"
      )
        partsCollected = partsCollected + 1;

      player.playSound(partsCollected < 3 ? "note.bell" : "random.levelup");

      buddy.nameTag = `Build your buddy!\n§a${partsCollected}§r/3 Parts`;

      if (partsCollected >= 3) {
        buddy.dimension.spawnParticle("arcedge_bap:appear", {
          x: buddy.location.x,
          y: buddy.location.y + 1,
          z: buddy.location.z,
        });
        system.runTimeout(() => {
          buddy.triggerEvent("arcedge_bap:despawn_buddy_builder");
          const buddyAlive = player.dimension.spawnEntity(
            "arcedge_bap:buddy",
            buddy.location,
            { spawnEvent: "arcedge_bap:init" }
          );

          if (checkBuddyProperties(1, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_axoltol_abilities");
          if (checkBuddyProperties(3, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_elephant_abilities");
          if (checkBuddyProperties(7, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_lion_abilities");
          if (checkBuddyProperties(9, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_mouse_abilities");
          if (checkBuddyProperties(10, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_panther_abilities");
          if (checkBuddyProperties(11, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_parrot_abilities");
          if (checkBuddyProperties(14, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_tiger_abilities");
          if (checkBuddyProperties(15, buddy))
            buddyAlive.triggerEvent("arcedge_bap:buddy_turtle_abilities");

          if(buddy.getProperty("arcedge_bap:head_part") == buddy.getProperty("arcedge_bap:torso_part") && buddy.getProperty("arcedge_bap:torso_part") == buddy.getProperty("arcedge_bap:legs_part")) {
            buddyAlive.triggerEvent("arcedge_bap:increase_base_stats")
          }
          buddyAlive.setProperty(
            "arcedge_bap:head_part",
            buddy.getProperty("arcedge_bap:head_part")
          );
          buddyAlive.setProperty(
            "arcedge_bap:torso_part",
            buddy.getProperty("arcedge_bap:torso_part")
          );
          buddyAlive.setProperty(
            "arcedge_bap:legs_part",
            buddy.getProperty("arcedge_bap:legs_part")
          );

          buddyAlive.nameTag = randomBuddyName();
          buddyAlive.getComponent("minecraft:tameable").tame(player);

          if (
            player.getDynamicProperty("first_buddy_interact_default") == false
          ) {
            player.sendMessage([
              {
                translate: "arcedge_bap.buddy.summon",
                with: [":_input_key.use:"],
              },
            ]);
            player.setDynamicProperty("first_buddy_interact_default", true);
          }
          if (
            checkBuddyProperties(15, buddy) &&
            player.getDynamicProperty("first_buddy_interact_turtle_special") ==
              false
          ) {
            player.sendMessage([
              {
                translate: "arcedge_bap.buddy.summon_turtle_special",
                with: [":_input_key.sneak:", ":_input_key.use:"],
              },
            ]);
            player.setDynamicProperty(
              "first_buddy_interact_turtle_special",
              true
            );
          }
        }, 1);
      }
    });
  }
  if (buddy.typeId === "arcedge_bap:buddy") {
    const tameable = buddy.getComponent("minecraft:tameable");

    if (tameable.tamedToPlayer !== player) {
      return player.sendMessage([
        { translate: "arcedge_bap.buddy.interact_error" },
      ]);
    }

    const sleeping = buddy.getProperty("arcedge_bap:sleeping");
    const holdingFoodItem =
      (getBuddyFoodIndex(slotMainHand?.typeId)?.index ?? -1) + 1;

    const buddyHealth = buddy.getComponent("minecraft:health");

    if (!checkBuddyProperties(holdingFoodItem, buddy) && slotMainHand?.typeId != 'arcedge_bap:buddy_stuffing') {
      system.run(() => {
        buddy.dimension.playSound("arcedge_bap.buddy.interact", buddy.location);
      });
    }
    if (
      holdingFoodItem &&
      checkBuddyProperties(holdingFoodItem, buddy) &&
      buddyHealth.currentValue != buddyHealth.effectiveMax
    ) {
      system.run(() => {
        if (slotMainHand.amount > 1) {
          slotMainHand.amount -= 1;
          equippedItem.setEquipment(EquipmentSlot.Mainhand, slotMainHand);
        } else {
          equippedItem.setEquipment(EquipmentSlot.Mainhand, undefined);
        }

        buddy.addEffect("instant_health", 1, {
          amplifier: 1,
          showParticles: true,
        });
        buddy.runCommand("playsound random.eat @a ~~~");
      });
    } else if (
      holdingFoodItem &&
      checkBuddyProperties(holdingFoodItem, buddy) == false
    ) {
      const buddyIdFirstSplit = slotMainHand.typeId.split(":")[1];
      const buddyIdSecondSplit = buddyIdFirstSplit.split("_")[0];
      const displayName =
        buddyIdSecondSplit.charAt(0).toUpperCase() +
        buddyIdSecondSplit.slice(1);

      player.sendMessage([
        {
          translate: "arcedge_bap.buddy.interact_food_error",
          with: [displayName],
        },
      ]);
    }

    system.run(() => {
      if (
        (holdingFoodItem && checkBuddyProperties(holdingFoodItem, buddy)) ||
        buddy.isInWater ||
        (player.isSneaking && checkBuddyProperties(15, buddy)) ||
        slotMainHand?.typeId == "minecraft:name_tag" ||
        slotMainHand?.typeId == "arcedge_bap:buddy_stuffing" ||
        slotMainHand?.typeId == "minecraft:lead" ||
        buddy.getComponent("minecraft:leashable").isLeashed
      )
        return;
      buddy.setProperty("arcedge_bap:sleeping", !sleeping);
      buddy.triggerEvent(
        sleeping
          ? "arcedge_bap:head_and_body_rotation_enabled"
          : "arcedge_bap:head_and_body_rotation_disabled"
      );
    });
  }
});

world.afterEvents.playerPlaceBlock.subscribe((data) => {
  const block = data.block;
  if (block.typeId == "arcedge_bap:dna_table")
    block.dimension.playSound("arcedge_bap.dna_table.place", block.location);
});

world.beforeEvents.playerBreakBlock.subscribe((data) => {
  const block = data.block;

  if (block.typeId == "arcedge_bap:dna_table")
    system.run(() => {
      block.dimension.playSound("arcedge_bap.dna_table.break", block.location);
    });
});
