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

let undoHolder = [];
let count = 0;
const RARE_CHANCE = 100;
const lastSpawn = {};
const MIN_COOLDOWN = 1000 * 60 * 60 * 24 * 3;

let form = new ActionFormData()
  .title("Build Structure")
  .body("Select structure type:")
  .button("Stone Pyramid", "textures/arts/b103ffba-f9cd-46a0-beb5-d69d62e076d8")
  .button("Stone Cross", "textures/arts/662dd6ac-44b4-48c7-87f4-4b6b505319d5")
  .button("Red Tunnel", "textures/arts/cf409911-1158-4558-b33d-75e067e4e432")
  .button("Undo Last Build", "textures/items/barrier");

world.afterEvents.playerPlaceBlock.subscribe(async (event) => {
  const player = event.player;
  const block = event.block;
  if (block.typeId !== "pa:constructor") return;

  const response = await form.show(player);
  if (response.canceled) return;

  const { x, y, z } = block;
  const chance = Math.floor(Math.random() * RARE_CHANCE);
  const now = Date.now();
  if (lastSpawn[player.name] && now - lastSpawn[player.name] < MIN_COOLDOWN) return;

  switch (response.selection) {
    case 0:
      if (chance < 1) {
        await buildStructure(player, x, y, z, "b103ffba-f9cd-46a0-beb5-d69d62e076d8", 4, 3, 4);
        lastSpawn[player.name] = now;
      }
      break;
    case 1:
      if (chance < 1) {
        await buildStructure(player, x, y, z, "662dd6ac-44b4-48c7-87f4-4b6b505319d5", 4, 6, 4);
        lastSpawn[player.name] = now;
      }
      break;
    case 2:
      if (chance < 1) {
        await buildStructure(player, x, y, z, "cf409911-1158-4558-b33d-75e067e4e432", 20, 4, 2);
        lastSpawn[player.name] = now;
      }
      break;
    case 3:
      await undoStructure(player);
      break;
  }
});

async function buildStructure(player, x, y, z, name, dx, dy, dz) {
  count++;
  const structureName = `${name}_${count}`;
  await player.runCommandAsync(`tickingarea add ${x} ${y} ${z} ${x + dx} ${y + dy} ${z + dz}`);
  await player.runCommandAsync(`structure save ${structureName} ${x} ${y} ${z} ${x + dx} ${y + dy} ${z + dz}`);
  undoHolder.push({ data: [{ name: structureName, x, y, z }] });
  await new Promise(r => setTimeout(r, 1000));
  await player.runCommandAsync(`structure load ${structureName} ${x} ${y} ${z}`);
  await player.runCommandAsync(`tickingarea remove_all`);
}

async function undoStructure(player) {
  if (undoHolder.length === 0) return;
  const data = undoHolder.pop();
  for (const item of data.data) {
    const { name, x, y, z } = item;
    await player.runCommandAsync(`tickingarea add ${x} 0 ${z} ${x} 0 ${z}`);
    await player.runCommandAsync(`structure delete ${name}`);
  }
  await player.runCommandAsync(`tickingarea remove_all`);
}