import { ItemStack, world, system } from "@minecraft/server";
import { getAdjacentBlock } from "./multiblockUtility.js";
import { UPGroupManager } from "./UPGroupManager.js";
import { highlightBlock } from "../blockHighlight.js";

/**
 * Called when the bottom block is placed or activated.
 */
export function multiblockUPFormationManager(block) {
  const statePlaced = block.permutation.getState("pb_gat:mb_placed");
  if (!statePlaced) {
    const blockAbove = getAdjacentBlock(block, "above");
    if (blockAbove.typeId !== "minecraft:air") {
      block.dimension.spawnItem(new ItemStack(block.typeId), block.location);
      block.setType("minecraft:air");
      const dim = block.dimension;
      const players = dim.getPlayers({
        location: block.location,
        maxDistance: 5,
      });
      const player = players[0];
      if (player) {
        player.playSound("note.bass", {
          pitch: 0.9,
          volume: 0.6,
          location: player.location,
        });
        highlightBlock(blockAbove, "red", "blocked");
        system.runTimeout(() => {
          highlightBlock(blockAbove, "red", "blocked");
          system.runTimeout(() => {
            highlightBlock(blockAbove, "red", "blocked");
          }, 20);
        }, 20);
        return player.sendMessage(
          "§4->§r No room for Upgrade Puncher, please ensure the block above is free."
        );
      }
      return;
    }

    // Place top block
    blockAbove.setType("pb_gat:mb_upgrade_puncher_top");

    const direction = block.permutation.getState(
      "minecraft:cardinal_direction"
    );
    blockAbove.setPermutation(
      blockAbove.permutation.withState(
        "minecraft:cardinal_direction",
        direction
      )
    );
    blockAbove.setPermutation(
      blockAbove.permutation.withState("pb_gat:mb_placed", true)
    );

    // Spawn entity
    const spawnLocation = {
      x: block.location.x + 0.5,
      y: block.location.y,
      z: block.location.z + 0.5,
    };
    const puncherEntity = block.dimension.spawnEntity(
      "pb_gat:mb_upgrade_puncher_entity",
      spawnLocation
    );
    if (puncherEntity) puncherEntity.setProperty("pb_gat:direction", direction);

    // Update bottom block state
    block.setPermutation(block.permutation.withState("pb_gat:mb_placed", true));

    // Register the group
    UPGroupManager.createGroup({
      direction,
      master: block,
      blocks: [blockAbove],
      entity: puncherEntity, // store the entity directly
    });
  } else {
    checkUPIntegrity(block);
  }
}

/**
 * Called on the top block (dummy), to ensure the bottom still exists.
 */
export function multiblockUPDummyBlockCheck(block) {
  checkUPIntegrity(block);
}

/**
 * Shared function for checking structure integrity.
 * Destroys blocks/entities if any part is missing or orphaned.
 */
function checkUPIntegrity(block) {
  const dim = block.dimension;
  const groupId = UPGroupManager.getGroupIdAtBlock(block);

  if (!groupId) {
    destroyBlockAndEntity(block, null);
    return;
  }

  const group = UPGroupManager.getGroup(groupId);
  if (!group) {
    destroyBlockAndEntity(block, null);
    return;
  }

  const bottom = dim.getBlock(group.master);
  const top = dim.getBlock(group.blocks[0]);
  const entity = group.entity;

  const bottomIsValid = bottom?.typeId === "pb_gat:mb_upgrade_puncher_bottom";
  const topIsValid = top?.typeId === "pb_gat:mb_upgrade_puncher_top";
  const entityIsValid = entity && !entity.isRemoved;

  if (!bottomIsValid || !topIsValid || !entityIsValid) {
    if (bottomIsValid)
      dim.spawnItem(
        new ItemStack("pb_gat:mb_upgrade_puncher_bottom"),
        bottom.location
      );

    if (
      bottom &&
      (bottom.typeId === "pb_gat:mb_upgrade_puncher_bottom" ||
        bottom.typeId === "pb_gat:mb_upgrade_puncher_top")
    ) {
      bottom.setType("minecraft:air");
    }
    if (
      top &&
      (top.typeId === "pb_gat:mb_upgrade_puncher_bottom" ||
        top.typeId === "pb_gat:mb_upgrade_puncher_top")
    ) {
      top.setType("minecraft:air");
    }

    // Remove only the entity from the group
    if (entity) {
      const entities = dim
        .getEntities({ type: "pb_gat:mb_upgrade_puncher_entity" })
        .filter((e) => e.id === entity.id);
      for (const e of entities) e.triggerEvent("pb_gat:drop_item_despawn");
    }

    UPGroupManager.destroyGroup(groupId);
  }
}

// Helper to destroy an orphan block and its entity from group data
function destroyBlockAndEntity(block, entity) {
  const dim = block.dimension;

  if (
    block.typeId === "pb_gat:mb_upgrade_puncher_bottom" ||
    block.typeId === "pb_gat:mb_upgrade_puncher_top"
  ) {
    dim.spawnItem(new ItemStack(block.typeId), block.location);
    block.setType("minecraft:air");
  }

  if (entity) {
    const entities = dim
      .getEntities({ type: "pb_gat:mb_upgrade_puncher_entity" })
      .filter((e) => e.id === entity.id);
    for (const e of entities) e.triggerEvent("pb_gat:drop_item_despawn");
  }
}
