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

export function multiblockGAMFormationManager(block) {
  const state = block.permutation.getState("pb_gat:mb_connection");
  if (state !== "single") {
    checkIntegrity(block);
  } else {
    checkFormation(block);
  }
}

function checkFormation(manager) {
  const direction = manager.permutation.getState(
    "minecraft:cardinal_direction"
  );
  const requiredType = manager.typeId;

  // Get surrounding blocks
  const left = getAdjacentBlock(manager, "left");
  const right = getAdjacentBlock(manager, "right");
  const above = getAdjacentBlock(manager, "above");
  const aboveLeft = getAdjacentBlock(left, "above");
  const aboveRight = getAdjacentBlock(right, "above");

  const multiblockParts = [left, right, above, aboveLeft, aboveRight];

  // Validate all blocks
  for (const b of multiblockParts) {
    if (!b) return;
    if (b.typeId !== requiredType) return;
    if (b.permutation.getState("pb_gat:mb_connection") !== "single") return;
    if (b.permutation.getState("minecraft:cardinal_direction") !== direction)
      return;
  }

  // Determine lever location
  const leverOffset = {
    south: { x: -1, z: 0 },
    north: { x: 1, z: 0 },
    west: { x: 0, z: -1 },
    east: { x: 0, z: 1 },
  };

  const front = leverOffset[direction];
  if (!front) return;

  const spawnLocation = {
    x: right.location.x + front.x + 0.5,
    y: right.location.y + 1,
    z: right.location.z + front.z + 0.5,
  };
  const leverBlock = right.dimension.getBlock(spawnLocation);
  if (!leverBlock || leverBlock.typeId !== "minecraft:air") {
    // Break the structure
    const allBlocks = [manager, ...multiblockParts];
    const dim = right.dimension;

    for (const b of allBlocks) {
      const block = dim.getBlock(b.location);
      if (block) {
        block.dimension.spawnItem(new ItemStack(block.typeId), block.location);
        block.setType("minecraft:air");
      }
    }

    // Notify the closest player
    const players = dim.getPlayers({
      location: manager.location,
      maxDistance: 5,
    });
    const player = players[0];
    if (player) {
      player.playSound("note.bass", {
        pitch: 0.9,
        volume: 0.6,
        location: leverBlock.location,
      });
      highlightBlock(leverBlock, "red", "blocked");
      system.runTimeout(() => {
        highlightBlock(leverBlock, "red", "blocked");
        system.runTimeout(() => {
          highlightBlock(leverBlock, "red", "blocked");
        }, 20);
      }, 20);
      return player.sendMessage(
        "§4->§r Multiblock formation failed - lever space is blocked."
      );
    }

    return;
  }
  const leverEntity = right.dimension.spawnEntity(
    "pb_gat:mb_gam_lever_entity",
    spawnLocation
  );
  if (leverEntity) {
    leverEntity.setProperty("pb_gat:direction", direction);
  }
  // Update states
  setBlockState(manager, "bottom_center");
  setBlockState(left, "bottom_left");
  setBlockState(right, "bottom_right");
  setBlockState(above, "top_center");
  setBlockState(aboveLeft, "top_left");
  setBlockState(aboveRight, "top_right");

  return GAMGroupManager.createGroup({
    direction,
    master: manager,
    blocks: multiblockParts,
    lever: leverEntity,
  });
}

function checkIntegrity(block) {
  const groupId = GAMGroupManager.getGroupIdAtBlock(block);
  if (!groupId) {
    // Block claims to be in a group, but no group found = force reset
    resetToSingle(block);
    return;
  }

  const group = GAMGroupManager.getGroup(groupId);
  if (!group) {
    resetToSingle(block);
    return;
  }

  const dim = block.dimension;
  const requiredType = block.typeId;
  const direction = group.direction;

  const allBlockLocations = [group.master, ...group.blocks];

  const isValid = allBlockLocations.every((loc) => {
    const b = dim.getBlock(loc);
    return (
      b &&
      b.typeId === requiredType &&
      b.permutation.getState("pb_gat:mb_connection") !== "single" &&
      b.permutation.getState("minecraft:cardinal_direction") === direction
    );
  });

  if (!isValid) {
    // Teardown the whole group
    GAMGroupManager.destroyGroup(groupId);
  }

  // 🔍 After teardown, if this block is no longer part of any group, reset it
  const stillInGroup = GAMGroupManager.getGroupIdAtBlock(block);
  if (!stillInGroup) {
    resetToSingle(block);
  }
}

function resetToSingle(block) {
  try {
    const newPerm = block.permutation
      .withState("pb_gat:mb_connection", "single")
      .withState("pb_gat:mb_has_item", false);
    block.setPermutation(newPerm);
  } catch (e) {}
}

function setBlockState(block, connectionState) {
  try {
    highlightBlock(block, "orange", "gear");

    // Update the permutation
    const perm = block.permutation.withState(
      "pb_gat:mb_connection",
      connectionState
    );
    block.setPermutation(perm);

    // If the connection state has "top" in its name, spawn extra particle
    if (connectionState.includes("top")) {
      block.dimension.spawnParticle(
        "minecraft:campfire_smoke_particle", // Example particle, replace with your own
        {
          x: block.location.x + 0.5,
          y: block.location.y + 1,
          z: block.location.z + 0.5,
        }
      );
    }
    world.playSound("item.spyglass.use", block.location, {
      pitch: 0.5,
      volume: 5.0,
    });
  } catch (e) {}
}
