// © Float Studios, 2024

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

let isFormBeingProcessed = false;

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

  isFormBeingProcessed = true;

  try {
    let ow = world.getDimension("overworld");
    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 showXPBar = nearestPlayer.hasTag("show_xp_bar");
      const bookOnDeath = nearestPlayer.hasTag("book_on_death");
      const isEvil = nearestPlayer.hasTag("evil");
      const isGood = nearestPlayer.hasTag("good");

      const form = new ModalFormData()
        .title({ translate: "warning.float_ad:settings.title" })
        .toggle({ translate: "warning.float_ad:settings.show_xp_bar" }, showXPBar)
        .toggle({ translate: "warning.float_ad:settings.book_on_death" }, bookOnDeath);

      if (message !== "hub") {
        form
          .toggle({ translate: "warning.float_ad:settings.hooded_spawn_confirmation" }, false)
          .toggle({ translate: "warning.float_ad:settings.hub_pearl" }, false);
      }

      const response = await form.show(nearestPlayer);

      if (!response.isCanceled && response.formValues !== undefined) {
        const [proceedWithShowXPBar, bookondeathresponse, spawnHooded, giveHubPearl] = response.formValues;

        // Process the first toggle (Show XP Bar)
        if (proceedWithShowXPBar) {
          nearestPlayer.addTag("show_xp_bar");
        } else {
          nearestPlayer.removeTag("show_xp_bar");
        }

        if (bookondeathresponse) {
          nearestPlayer.addTag("book_on_death");
        } else {
          nearestPlayer.removeTag("book_on_death");
        }

        if (message !== "hub") {
          // Process the second toggle (Hooded Spawning)
          for (const player of players) {
            if (spawnHooded) {
              try {
                const structureName = "float_ad/intro_npc";
                const viewDirection = player.getRotation();
                const radians = (viewDirection.y + 90) * (Math.PI / 180); // Adjusted to locate in front of the player
                const startX = player.location.x + Math.cos(radians) * 4;
                const startY = player.location.y;
                const startZ = player.location.z + Math.sin(radians) * 4;

                const loadCommand = `structure load "${structureName}" ${startX} ${startY + 1} ${startZ}`;

                const blockAbove = ow.getBlock({ x: startX, y: startY, z: startZ });
                const blockBelow = ow.getBlock({ x: startX, y: startY - 1, z: startZ });

                if (blockAbove.typeId === "minecraft:air" && blockBelow.typeId !== "minecraft:air") {
                  system.runTimeout(() => {
                    const playerCheck = [...world.getPlayers()].find((p) => p.id === player.id);
                    if (playerCheck) {
                      world.getDimension("overworld").runCommand(loadCommand);
                    }
                  }, 5); // Delay of 200ms to ensure the player is in the game

                  return;
                }

                for (let dx = -3; dx <= 3; dx++) {
                  for (let dz = -3; dz <= 3; dz++) {
                    const x = player.location.x + dx;
                    const y = player.location.y;
                    const z = player.location.z + dz;
                    const blockAbove = ow.getBlock({ x: x, y: y, z: z });
                    const blockBelow = ow.getBlock({ x: x, y: y - 1, z: z });
                    if (blockAbove.typeId === "minecraft:air" && blockBelow.typeId !== "minecraft:air") {
                      const loadCommand2 = `structure load "${structureName}" ${x} ${y + 1} ${z}`;
                      system.runTimeout(() => {
                        const playerCheck = [...world.getPlayers()].find((p) => p.id === player.id);
                        if (playerCheck) {
                          world.getDimension("overworld").runCommand(loadCommand2);
                        }
                      }, 5); // Delay of 200ms to ensure the player is in the game
                      return;
                    }
                  }
                }
              } catch {
                console.error(`Error spawning Hooded Figure for ${player.name}. Try a different Location.`);
              }
            }
          }

          // Process the third toggle (Give Hub Pearl)
          if (giveHubPearl) {
            if (isEvil || isGood) {
              const itemStack = new ItemStack(isEvil ? "float_ad:evil_hub_pearl" : "float_ad:good_hub_pearl", 1);

              // Add lore to the item
              const itemLore = [
                isEvil ? "§8Use to Teleport to the Demon Hub Realm" : "§8Use to Teleport to the Angel Hub Cloud",
              ];
              itemStack.setLore(itemLore);

              const inventory = nearestPlayer.getComponent("minecraft:inventory").container;

              // Remove all existing pearls from the inventory
              nearestPlayer.runCommand(`clear "${nearestPlayer.name}" float_ad:good_hub_pearl`);
              nearestPlayer.runCommand(`clear "${nearestPlayer.name}" float_ad:evil_hub_pearl`);

              // Add the new pearl to the inventory
              inventory.addItem(itemStack);
            }
          }
        }
      }
    } else {
      console.log("No players found near the source entity.");
    }
  } catch (error) {
    console.error("Failed to show form:", error);
  } finally {
    isFormBeingProcessed = false;
  }
}
