import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { world, system } from "@minecraft/server";

let isFormBeingProcessed = false;

export default async function showsettings(sourceEntity) {
  if (isFormBeingProcessed) {
    return;
  }

  isFormBeingProcessed = true;

  try {
    const dimension = sourceEntity.dimension;
    const players = dimension.getPlayers();
    let nearestPlayer = null;
    let minDistance = Infinity;

    // Find the nearest player to the sourceEntity
    for (const player of players) {
      const distance = Math.sqrt(
        Math.pow(player.location.x - sourceEntity.location.x, 2) +
          Math.pow(player.location.y - sourceEntity.location.y, 2) +
          Math.pow(player.location.z - sourceEntity.location.z, 2)
      );

      if (distance < minDistance) {
        minDistance = distance;
        nearestPlayer = player;
      }
    }

    // Check if a valid nearest player was found
    if (nearestPlayer) {
      const tree_spawning = world.getDynamicProperty("no_tree_spawning");
      const spawningdisabled = tree_spawning;
      const traderspawningenabled = nearestPlayer.hasTag("trader_spawn");

      const form = new ModalFormData()
        .title({ translate: "warning.float_fc:settings.title" })
        .toggle({ translate: "warning.float_fc:settings.confirmation" }, spawningdisabled)
        .toggle({ translate: "warning.float_br:settings.confirmation2" }, traderspawningenabled);

      const response = await form.show(nearestPlayer);

      if (!response.isCanceled && response.formValues !== undefined) {
        console.log("Form response:", JSON.stringify(response));

        const [proceedWithRemoval, proceedWithTraderSpawn] = response.formValues;

        const treeSpawnTag = `no_tree_spawning`;
        if (proceedWithRemoval) {
          world.setDynamicProperty(treeSpawnTag, true);
        } else {
          world.setDynamicProperty(treeSpawnTag, false);
        }

        // Process the second toggle (Trader Spawning)
        for (const player of players) {
          if (proceedWithTraderSpawn) {
            player.addTag("trader_spawn");
          } else {
            player.removeTag("trader_spawn");
          }
        }
      }
    } else {
      console.log("No players found near the source entity.");
    }
  } catch (error) {
    console.error("Failed to show form:", error);
  } finally {
    isFormBeingProcessed = false;
  }
}
