import { ItemStack } from "@minecraft/server";
import { getRandomNumber } from "./utils/helpers.js";

const updateCrossbow = (newTypeId, item, source) => {
  const newCrossbow = new ItemStack(newTypeId, 1);

  // Transfer enchantments
  const previousEnchantments = item.getComponent("minecraft:enchantable").getEnchantments();
  const newEnchantments = newCrossbow.getComponent("minecraft:enchantable");
  newEnchantments.addEnchantments(previousEnchantments);

  // Transfer name tag
  newCrossbow.nameTag = item.nameTag;

  // Transfer and adjust durability
  const previousDurability = item.getComponent("minecraft:durability").damage;
  const newDurability = newCrossbow.getComponent("minecraft:durability");
  newDurability.damage = previousDurability;
  if (!newTypeId.includes("_loaded")) {
    let decreaseDurability = 1

    for (const enchant of previousEnchantments) {
      if (enchant.type.id != "unbreaking") continue
      let chance = getRandomNumber(1, 100)
      if (enchant.level == 1) {
        if (chance <= 50) decreaseDurability = 0
      } else if (enchant.level == 2) {
        if (chance <= 66) decreaseDurability = 0
      } else if (enchant.level == 3) {
        if (chance <= 75) decreaseDurability = 0
      }
    }
    newDurability.damage = newDurability.damage + decreaseDurability;
  }

  // Equip the new crossbow
  const playerEquippable = source.getComponent("minecraft:equippable");
  playerEquippable.setEquipment("Mainhand", newCrossbow);
};

export async function playerCrossbowUse(event) {
  const item = event.itemStack
  const player = event.source

  if (!item.typeId.includes("4ks_wp:") || (!item.typeId.includes("crossbow_loaded") && !item.typeId.includes("crossbow_piercing"))) return

  const headLocation = player.getHeadLocation();
  const viewDirection = player.getViewDirection();

  // Desired offset distance to the side
  const sideOffset = 1.5; // Adjust as needed

  // Calculate perpendicular vectors for left and right
  const leftOffset = {
    x: -viewDirection.z * sideOffset,
    y: 0,
    z: viewDirection.x * sideOffset
  };

  const rightOffset = {
    x: viewDirection.z * sideOffset,
    y: 0,
    z: -viewDirection.x * sideOffset
  };

  const velocity = {
    x: player.getViewDirection().x * 5,
    y: player.getViewDirection().y * 5,
    z: player.getViewDirection().z * 5,
  };

  if (!item.typeId.includes("crossbow_piercing")) {
    const middleProjectile = player.dimension.spawnEntity("4ks_wp:crossbow_arrow", {
      x: headLocation.x + viewDirection.x * 1,
      y: headLocation.y + viewDirection.y * 1,
      z: headLocation.z + viewDirection.z * 1
    });


    const middleProjectileComp = middleProjectile.getComponent('minecraft:projectile');
    middleProjectileComp.owner = player

    middleProjectileComp?.shoot(velocity)
  }

  let multishotLevel = 1
  const enchantable = item.getComponent('minecraft:enchantable');
  for (const enchant of enchantable.getEnchantments()) {
    if (enchant.type.id == "multishot") {
      multishotLevel = enchant.level + 1
      const leftProjectile = player.dimension.spawnEntity("4ks_wp:scatter_arrow", {
        x: headLocation.x + viewDirection.x * 1,
        y: headLocation.y + viewDirection.y * 1,
        z: headLocation.z + viewDirection.z * 1
      });

      const rightProjectile = player.dimension.spawnEntity("4ks_wp:scatter_arrow", {
        x: headLocation.x + viewDirection.x * 1,
        y: headLocation.y + viewDirection.y * 1,
        z: headLocation.z + viewDirection.z * 1
      });

      const rightProjectileComp = rightProjectile.getComponent('minecraft:projectile');
      const leftProjectileComp = leftProjectile.getComponent('minecraft:projectile');

      rightProjectileComp.owner = player;
      leftProjectileComp.owner = player;

      const spreadAngle = 10 * (Math.PI / 180);

      const leftVelocity = {
        x: velocity.x * Math.cos(spreadAngle) - velocity.z * Math.sin(spreadAngle),
        y: velocity.y,
        z: velocity.x * Math.sin(spreadAngle) + velocity.z * Math.cos(spreadAngle)
      };

      const rightVelocity = {
        x: velocity.x * Math.cos(-spreadAngle) - velocity.z * Math.sin(-spreadAngle),
        y: velocity.y,
        z: velocity.x * Math.sin(-spreadAngle) + velocity.z * Math.cos(-spreadAngle)
      };

      rightProjectileComp?.shoot(rightVelocity);
      leftProjectileComp?.shoot(leftVelocity);
    }
  }

  if (item.typeId.includes("scatter")) {
    for (let i = 0; i < multishotLevel * 5; i++) {
      // Randomize the velocity for scatter effect
      const scatterVelocity = {
        x: velocity.x + (Math.random() - 0.5) * 2, // Adjust scatter intensity
        y: velocity.y + (Math.random() - 0.5) * 2,
        z: velocity.z + (Math.random() - 0.5) * 2,
      };

      // Normalize the velocity to maintain consistent speed
      const magnitude = Math.sqrt(
        scatterVelocity.x ** 2 +
        scatterVelocity.y ** 2 +
        scatterVelocity.z ** 2
      );

      scatterVelocity.x = (scatterVelocity.x / magnitude) * 5;
      scatterVelocity.y = (scatterVelocity.y / magnitude) * 5;
      scatterVelocity.z = (scatterVelocity.z / magnitude) * 5;

      const scatterProjectile = player.dimension.spawnEntity("4ks_wp:scatter_arrow", {
        x: headLocation.x + viewDirection.x * 1.5,
        y: headLocation.y + viewDirection.y * 1.5,
        z: headLocation.z + viewDirection.z * 1.5,
      });

      const scatterProjectileComp = scatterProjectile.getComponent('minecraft:projectile');
      scatterProjectileComp.owner = player;

      scatterProjectileComp?.shoot(scatterVelocity);
    }
  }

  player.runCommand(`/playsound crossbow.shoot @a ~~~`)
  player.setDynamicProperty(`4ks_wp:last_used_bow`, item?.typeId)
  updateCrossbow(`${item.typeId.replace("_loaded", "")}`, item, player)

}