import { world, system } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { cachedPlayers } from '../lag/pvp.js';

const overworld = world.getDimension("overworld");

// === CONFIG ===
const PLOT_PRICE = 5000000; // 5M
const PLOTS = {
  1: { min: { x: 9894, y: 4, z: 9933 }, max: { x: 9950, y: 4, z: 9989 } },
  2: { min: { x: 9972, y: 4, z: 9933 }, max: { x: 10028, y: 4, z: 9989 } },
  3: { min: { x: 10050, y: 4, z: 9933 }, max: { x: 10106, y: 4, z: 9989 } },
  4: { min: { x: 9894, y: 4, z: 10011 }, max: { x: 9950, y: 4, z: 10067 } },
  5: { min: { x: 9972, y: 4, z: 10011 }, max: { x: 10028, y: 4, z: 10067 } },
  6: { min: { x: 10050, y: 4, z: 10011 }, max: { x: 10106, y: 4, z: 10067 } },
  7: { min: { x: 9894, y: 4, z: 10089 }, max: { x: 9950, y: 4, z: 10145 } },
  8: { min: { x: 9972, y: 4, z: 10089 }, max: { x: 10028, y: 4, z: 10145 } },
  9: { min: { x: 10050, y: 4, z: 10089 }, max: { x: 10106, y: 4, z: 10145 } },
};

// === DYNAMIC PROPERTIES INIT ===
world.afterEvents.worldInitialize.subscribe(ev => {
  const def = ev.propertyRegistry;
  for (const id in PLOTS) {
    def.registerWorldDynamicProperty(`plot${id}Owner`, "string");
  }
});


// === EVENTS ===
world.afterEvents.entityHitEntity.subscribe(event => {
  const { damagingEntity, hitEntity } = event;
  if (damagingEntity?.typeId !== "minecraft:player") return;
  if (hitEntity?.typeId === "npc:npc_custom6") {
    openPlotManagement(damagingEntity);
    damagingEntity.runCommandAsync("playsound random.pop2");
  }
});

world.afterEvents.playerInteractWithEntity.subscribe(event => {
  const { player, target } = event;
  if (target?.typeId === "npc:npc_custom6") {
    openPlotManagement(player);
    player.runCommandAsync("playsound random.pop2");
  }
});

// === UTILS ===
export function getOwner(id) {
  return world.getDynamicProperty(`plot${id}Owner`);
}
function setOwner(id, name) {
  world.setDynamicProperty(`plot${id}Owner`, name);
}
function clearOwner(id) {
  world.setDynamicProperty(`plot${id}Owner`, undefined);
}

export function openPlotManagement(player) {
  const form = new ActionFormData()
    .title("§l§aPlot Manager")
    .body("Choose an option:")
    .button("§aBuy Plots\n§7Tap To View")
    .button("§cSell Plots\n§7Tap To View")
    .button("§dYour Plots\n§7Tap To View")
    .button("§5Teleport to Plots\n§7Tap To View")
    .button("§bCreative Blocks\n§7Tap To Teleport");

  // === Admin-only extra button ===
  if (player.hasTag("gwim:Admin")) {
    form.button("§4[ADMIN] Reset Other Plots\n§7Manage Players Plots");
  }

  form.show(player).then(res => {
    if (res.canceled) return;

    const isAdmin = player.hasTag("gwim:Admin");

    switch (res.selection) {
      case 0: showBuyPlots(player); break;
      case 1: showSellPlots(player); break;
      case 2: showYourPlots(player); break;
      case 3: showTpPlots(player); break;
      case 4: enterCreativeBlocks(player); break;
      case 5: if (isAdmin) showAdminResetMenu(player); break;
    }
  });
}

function showAdminResetMenu(player) {
  const form = new ActionFormData()
    .title("§4§lADMIN Reset Plots")
    .body("Select a plot to reset. This will remove its owner.");

  for (let id in PLOTS) {
    const owner = getOwner(id);
    form.button(owner ? `Plot ${id}\n§cOwned by ${owner}` : `Plot ${id}\n§aAlready Free`);
  }
  form.button("§cBack", "textures/ui/arrow_left");

  form.show(player).then(res => {
    if (res.canceled) return;
    if (res.selection === Object.keys(PLOTS).length) return openPlotManagement(player);

    const id = res.selection + 1;
    adminResetPlot(player, id);
  });
}

function adminResetPlot(player, id) {
  const owner = getOwner(id);

  if (!owner) {
    player.sendMessage(`§ePlot ${id} is already free.`);
    player.playSound("note.bass");
    return;
  }

  clearOwner(id); // direct reset
  world.sendMessage(`§c[ADMIN] §l${player.name} §r§creset Plot ${id}, removing owner §6§l${owner}§r`);
  player.playSound("random.explode");

  // Notify the owner if they are online
  for (const onlinePlayer of cachedPlayers) {
    if (onlinePlayer.name === owner) {
      onlinePlayer.sendMessage(`§cYour Plot ${id} has been reset by an §4Admin§c!`);
      onlinePlayer.playSound("note.bass");
      break;
    }
  }
}

function enterCreativeBlocks(player) {
  let ownsPlot = false;

  for (let id in PLOTS) {
    if (getOwner(id) === player.name) {
      ownsPlot = true;
      break;
    }
  }

  if (!ownsPlot) {
    player.sendMessage("§cYou must own a plot to enter the Creative Blocks area!");
    player.playSound("note.bass");
    return;
  }

  // Teleport to Creative Blocks area
  player.teleport({ x: 10000, y: 4, z: 9896 }, overworld);
  

  // Extra effects after entering
  system.runTimeout(() => {
    player.runCommandAsync(`particle minecraft:knockback_roar_particle ~ ~ ~`);
    player.runCommandAsync(`clearspawnpoint @s`);
    player.addEffect("blindness", 20, {
      amplifier: 0,
      showParticles: false
    });
    player.playSound("mob.endermen.portal");
  }, 1); // delay by 1 tick (~50ms)
}


function showBuyPlots(player) {
  const form = new ActionFormData()
    .title("§l§7Buy Plots")
    .body("Each plot costs 5M Money:");

  for (let id in PLOTS) {
    const owner = getOwner(id);

    if (owner) {
      form.button(`Plot ${id}\n§cOwned by ${owner}`);
    } else {
      form.button(`Plot ${id}\n§aAvailable | §l$5M`);
    }
  }

  form.button('§c§lBack', "textures/ui/arrow_left");

  form.show(player).then(res => {
    if (res.canceled) return;
    if (res.selection === Object.keys(PLOTS).length) return openPlotManagement(player);

    const id = res.selection + 1;

    // Only let them try to buy if plot is free
    if (getOwner(id)) {
      player.sendMessage(`§cPlot ${id} is already owned by §l${getOwner(id)}§r`);
      player.playSound("note.bass");
      return;
    }

    buyPlot(player, id);
  });
}

function buyPlot(player, id) {
  // Check if player already owns 2 plots
  let ownedCount = 0;
  for (let pid in PLOTS) {
    if (getOwner(pid) === player.name) {
      ownedCount++;
    }
  }

  if (ownedCount >= 2) {
    player.sendMessage("§cYou can only own up to §l2 plots§r§c at a time!");
    player.playSound("note.bass");
    return;
  }

  // Check if the selected plot is available
  if (getOwner(id)) {
    player.sendMessage("§cThat plot is already sold.");
    player.playSound("note.bass");
    return;
  }

  // Check player money
  const score = world.scoreboard.getObjective("Money");
  const current = score.getScore(player) ?? 0;

  if (current < PLOT_PRICE) {
    player.sendMessage("§cYou don't have enough money!");
    player.playSound("note.bass");
    return;
  }

  // Deduct money and assign ownership
  score.setScore(player, current - PLOT_PRICE);
  setOwner(id, player.name);

  player.sendMessage(`§aYou bought Plot ${id}!`);
  player.playSound("random.orb");
}

// === SELL PLOTS ===
function showSellPlots(player) {
  const form = new ActionFormData().title("§l§7Sell Plots").body("Select a plot to sell:");
  let owned = [];
  for (let id in PLOTS) {
    if (getOwner(id) === player.name) {
      form.button(`Plot ${id}\n§cClick to sell`);
      owned.push(Number(id));
    }
  }
  if (owned.length === 0) {
    player.sendMessage("§cYou don't own any plots!");
    player.playSound("note.bass");
    return;
  }
  form.button('§cBack', "textures/ui/arrow_left");

  form.show(player).then(res => {
    if (res.canceled) return;
    if (res.selection === owned.length) return openPlotManagement(player);
    sellPlot(player, owned[res.selection]);
  });
}

function sellPlot(player, id) {
  if (getOwner(id) !== player.name) return;

  const score = world.scoreboard.getObjective("Money");
  const current = score.getScore(player) ?? 0;
  score.setScore(player, current + PLOT_PRICE);

  clearOwner(id);
  player.sendMessage(`§aYou sold Plot ${id} and got $5M!`);
  player.playSound("random.orb");
}

// === YOUR PLOTS ===
function showYourPlots(player) {
  const form = new ActionFormData().title("§l§7Your Plots").body("Select a plot to Teleport:");
  let owned = [];
  for (let id in PLOTS) {
    if (getOwner(id) === player.name) {
      form.button(`Plot ${id}\n§7Tap To Teleport`);
      owned.push(Number(id));
    }
  }
  if (owned.length === 0) {
    player.sendMessage("§cYou don't own any plots!");
    player.playSound("note.bass");
    return;
  }
  form.button('§cBack', "textures/ui/arrow_left");

  form.show(player).then(res => {
    if (res.canceled) return;
    if (res.selection === owned.length) return openPlotManagement(player);
    tpToPlot(player, owned[res.selection]);
  });
}

// === TP TO PLOTS ===
function showTpPlots(player) {
  const form = new ActionFormData().title("§l§7Teleport to Plots").body("Select a plot to Teleport:");
  for (let id in PLOTS) {
    form.button(`Plot ${id}\n§7Tap To Teleport`);
  }
  form.button('§cBack', "textures/ui/arrow_left");

  form.show(player).then(res => {
    if (res.canceled) return;
    if (res.selection === Object.keys(PLOTS).length) return openPlotManagement(player);
    tpToPlot(player, res.selection + 1);
  });
}

// === TP TO PLOTS ===
function tpToPlot(player, id) {
  const plot = PLOTS[id];
  if (!plot) return;

  const x = Math.floor(Math.random() * (plot.max.x - plot.min.x + 1)) + plot.min.x;
  const y = Math.floor(Math.random() * (plot.max.y - plot.min.y + 1)) + plot.min.y;
  const z = Math.floor(Math.random() * (plot.max.z - plot.min.z + 1)) + plot.min.z;

  player.teleport({ x, y, z }, overworld);
  player.sendMessage(`§aTeleported to a random spot in Plot ${id}`);

  system.runTimeout(() => {
    player.runCommandAsync(`particle minecraft:knockback_roar_particle ~ ~ ~`);
    player.addEffect("blindness", 20, {
      amplifier: 0,
      showParticles: false
    });
    player.playSound("mob.endermen.portal");
  }, 1); // delay by 1 tick (~50ms)
}