import { system, EquipmentSlot } from "@minecraft/server";
import * as utils from "../utils";
import * as camera from "../camera";
import { damageItem } from "../inventory_utils";

const CONFIG = {
  COOLDOWN: 3 * 20,
  EXPLOSION_RANGE: 5,
  EXPLOSION_DAMAGE: 16,
  KNOCKBACK_STRENGTH: 2,
  ANIMATION_DELAY: 15,
  EXPLOSION_DELAY: 10,
  CAMERA_DURATION: 30,
  TP_TRANSITION_DURATION: 0.5,
};

export async function onItemUse(event) {
  const player = event.source;
  damageItem(player, EquipmentSlot.Mainhand, 1);
  if (player.getItemCooldown("tcs_cwp:demolition_hammer") > 0) return;
  player.startItemCooldown("tcs_cwp:demolition_hammer", CONFIG.COOLDOWN);

  if (player.getGameMode() === "survival") damageItem(player, EquipmentSlot.Mainhand, 1);

  camera.switchToThirdPerson(player, CONFIG.TP_TRANSITION_DURATION);
  utils.playAnimation(player, "animation.tcs_cwp.demolition_hammer.smash");

  system.waitTicks(CONFIG.ANIMATION_DELAY).then(() => performExplosion(player));
  system
    .waitTicks(CONFIG.CAMERA_DURATION)
    .then(() =>
      camera.resetToFirstPerson(player, CONFIG.TP_TRANSITION_DURATION)
    );
}

function performExplosion(player) {
  const entities = utils.getAllEntitiesInRange(
    player.dimension,
    player.location,
    0,
    CONFIG.EXPLOSION_RANGE
  );
  utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=15]`, 'tcs_cwp:demolition_hammer_slam');
  utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=15]`, 'tcs_cwp:demolition_hammer_ground_punch');
  utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=15]`, 'tcs_cwp:demolition_hammer_ground_imact');
  player.dimension.spawnParticle(
    "tcs_cwp:ground_shake",
    player.location,
    undefined
  );
  const { x, y, z } = player.location;
  for (let dx = -2; dx <= 2; dx++) {
    for (let dz = -2; dz <= 2; dz++) {
      player.dimension.spawnParticle(
        "tcs_cwp:demolition_explosion",
        { x: x + dx, y, z: z + dz },
        undefined
      );
    }
  }
  player.dimension.spawnParticle(
    "tcs_cwp:ground_dust",
    player.location,
    undefined
  );
  player.dimension.spawnParticle(
    "tcs_cwp:ground_debris",
    player.location,
    undefined
  );
  entities.then((entities) => {
    for (const entity of entities) {
      if (entity.id === player.id) continue;
      if (
        entity.typeId === "minecraft:item" ||
        entity.typeId === "minecraft:xp_orb"
      )
        continue;

      const entityPos = entity.location;
      const playerPos = player.location;
      const dx = entityPos.x - playerPos.x;
      const dz = entityPos.z - playerPos.z;
      const distance = Math.sqrt(dx * dx + dz * dz);

      if (distance > 0) {
        const knockbackX = (dx / distance) * CONFIG.KNOCKBACK_STRENGTH;
        const knockbackZ = (dz / distance) * CONFIG.KNOCKBACK_STRENGTH;

        utils.applyKnockback(
          entity,
          knockbackX,
          knockbackZ,
          CONFIG.KNOCKBACK_STRENGTH,
          0.5
        );
      }

      utils.applyDamage(entity, CONFIG.EXPLOSION_DAMAGE);
    }
  });
}

export async function onEntityHit(event) {
  const attacker = event.damagingEntity;
  if (!attacker || attacker.typeId !== "minecraft:player") return;

  const target = event.hitEntity;
  if (!target) return;

  const heldItem = attacker
    .getComponent("minecraft:equippable")
    ?.getEquipment(EquipmentSlot.Mainhand);
  if (!heldItem || heldItem.typeId !== "tcs_cwp:demolition_hammer") return;

  attacker.startItemCooldown("tcs_cwp_animation_left_click", 5.3);
  utils.playAnimation(attacker, "animation.tcs_cwp.lighting_hammer.attack_2_tp");

  target.runCommandAsync(`particle tcs_cwp:demolition_hit ~ ~ ~`);
}