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 selectionbox = nearestPlayer.hasTag("selection_box");
      const currentRefreshRate = world.getDynamicProperty("float_mb:refresh_rate") || 3; // fallback if not stored
      const miniblockConversionSneakToggle =
        world.getDynamicProperty("float_mb:miniblockConvertionSneakToggle") || true; // fallback if not stored
      const miniblockConversion = world.getDynamicProperty("float_mb:miniblockConvertion") || false; // fallback if not stored

      const form = new ModalFormData()
        .title({ translate: "warning.float_mb:settings.title" })
        .toggle({ translate: "warning.float_mb:settings.selectionbox" }, selectionbox)
        .slider({ translate: "warning.float_mb:settings.refreshrate" }, 1, 10, 1, currentRefreshRate)
        .toggle(
          { translate: "warning.float_mb:settings.miniblockConversionSneakToggle" },
          miniblockConversionSneakToggle
        )
        .toggle({ translate: "warning.float_mb:settings.miniblockConversion" }, miniblockConversion);

      const response = await form.show(nearestPlayer);

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

        const [enableSelectionBox, refreshRate, SneakToggle, Conversion] = response.formValues;

        // Process the first toggle (Tree Spawning)
        for (const player of players) {
          if (enableSelectionBox) {
            player.addTag("selection_box");
          } else {
            player.removeTag("selection_box");
          }
        }
        for (const player of players) {
          const key = `float_mb:miniblockConvertion`;
          world.setDynamicProperty(key, Conversion);
          const key3 = `float_mb:miniblockConvertionSneakToggle`;
          world.setDynamicProperty(key3, SneakToggle);
          if (Conversion !== miniblockConversion) {
            player.sendMessage(`§eMiniBlock Conversion: ${!miniblockConversion ? "§aEnabled" : "§cDisabled"}`);
          }
        }
        // Process the second toggle (Refresh Rate)
        const key2 = `float_mb:refresh_rate`;
        world.setDynamicProperty(key2, refreshRate);
      }
    } else {
      console.log("No players found near the source entity.");
    }
  } catch (error) {
    console.error("Failed to show form:", error);
  } finally {
    isFormBeingProcessed = false;
  }
}
