import { world, system } from "@minecraft/server";
import {
  getAdjacentBlock,
  playerEquippedItem,
  mbEntityGiveItem,
  consumeItem,
  getMultiblockEntity,
  mbEntityDropItem,
} from "./multiblockUtility.js";
import { GAMGroupManager } from "./GAMGroupManager.js";
import { ALLOWED_ITEMS } from "./GAMRecipeList.js";

function playSound(player) {
  system.run(() => {
    player.playSound("note.bass", {
      pitch: 0.9,
      volume: 0.6,
      location: player.location,
    });
  });
}

//seperate interaction manager for single state feedback
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const block = event.block;
  const connectionState = block.permutation.getState("pb_gat:mb_connection");
  const player = event.player;
  const { selectedItem, equipment } = playerEquippedItem(player);

  if (block.typeId === "pb_gat:mb_gam" && connectionState === "single") {
    try {
      if (!selectedItem) {
        playSound(player);
        return player.sendMessage("§4->§r This machine is incomplete.");
      }
    } catch (error) {}
    if (selectedItem.typeId !== "pb_gat:mb_gam") {
      playSound(player);
      player.sendMessage("§4->§r This machine is incomplete.");
    }
  }
});

export function multiblockGAMInteractionManager(block, player) {
  const connectionState = block.permutation.getState("pb_gat:mb_connection");

  // Check if the group is currently running
  const groupId = GAMGroupManager.getGroupIdAtBlock(block);
  if (groupId) {
    const group = GAMGroupManager.getGroup(groupId);
    if (group?.running) {
      playSound(player);
      player.sendMessage(
        "§6->§r The machine is currently running. Please wait."
      );
      return;
    }
  }

  const hasItemState = block.permutation.getState("pb_gat:mb_has_item");

  if (!hasItemState) {
    placeItem(block, player);
  }

  if (hasItemState) {
    removeItem(block, player);
  }
}

function placeItem(block, player) {
  const { selectedItem, equipment } = playerEquippedItem(player);
  if (!selectedItem) {
    playSound(player);
    return player.sendMessage("§4->§r Please equip an item to place into the machine.");
  }

  const itemId = selectedItem.typeId;

  // ✅ Block items not in recipe list
  if (!ALLOWED_ITEMS.has(itemId)) {
    playSound(player);
    return player.sendMessage("§4->§r That item has no use in this machine.");
  }

  const spawnLocation = {
    x: block.location.x + 0.5,
    y: block.location.y,
    z: block.location.z + 0.5,
  };

  const mbEntity = block.dimension.spawnEntity(
    "pb_gat:mb_gam_entity",
    spawnLocation
  );

  if (!mbEntity) {
    return;
  }

  const connectionState = block.permutation.getState("pb_gat:mb_connection");
  const direction = block.permutation.getState("minecraft:cardinal_direction");

  if (connectionState && connectionState !== "single") {
    mbEntity.setProperty("pb_gat:position", connectionState);
  }

  if (direction) {
    mbEntity.setProperty("pb_gat:direction", direction);
  }

  // Mark block as containing an item
  block.setPermutation(block.permutation.withState("pb_gat:mb_has_item", true));
  world.playSound("random.pop", block.location);

  mbEntityGiveItem(mbEntity, selectedItem);
  consumeItem(player, selectedItem, equipment);

  // ✅ Register with the multiblock group
  const groupId = GAMGroupManager.getGroupIdAtBlock(block);
  if (groupId) {
    GAMGroupManager.addItemEntity(groupId, mbEntity);
  }
}

function removeItem(block, player) {
  const mbEntity = getMultiblockEntity(block, "pb_gat_mb_gam");
  if (mbEntity) {
    world.playSound("random.pop2", block.location);

    // Drop the item to the player
    mbEntityDropItem(mbEntity, block, player);

    // ✅ Remove from group
    const groupId = GAMGroupManager.getGroupIdAtBlock(block);
    if (groupId) {
      GAMGroupManager.removeItemEntity(groupId, mbEntity.id);
    }
  } else {
    return;
  }

  // Mark the block as no longer holding an item
  block.setPermutation(
    block.permutation.withState("pb_gat:mb_has_item", false)
  );
}
