import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { showArtilleryControlUI } from "../TankControlUI.js";


const EXCLUDED_ENTITIES = [
  "minecraft:item",
  "minecraft:xp_orb",
  "minecraft:arrow",
  "minecraft:snowball",
  "minecraft:egg",
  "minecraft:ender_pearl",
  "minecraft:trident",
  "minecraft:fireball",
  "minecraft:small_fireball",
  "minecraft:dragon_fireball",
  "minecraft:wither_skull",
  "minecraft:fishing_hook",
  "minecraft:splash_potion",
  "minecraft:lingering_potion",
  
];


const RADAR_RANGE = 30;
const GRID_SIZE = 11;
const GRID_CENTER = Math.floor(GRID_SIZE / 2);


const directions = ["S", "SW", "W", "NW", "N", "NE", "E", "SE"];

/**
 * Convert rotation degrees to one of ["S","SW","W","NW","N","NE","E","SE"].
 */
function getDirectionString(rotation) {
  let index = Math.floor(((rotation + 180) % 360) / 45);
  if (index < 0) index += 8;
  return directions[index];
}

/** Convert degrees to radians */
function degToRad(deg) {
  return (deg * Math.PI) / 180;
}

/**
 * Rotates (dx, dz) by -rotation so that "front" => negative z'.
 * This ensures an entity physically in front of the tank
 * is placed "above" the tank in our ASCII grid (row<5).
 */
function transformToLocal(dx, dz, rotationDeg) {
  const θ = degToRad(-rotationDeg);
  const cosθ = Math.cos(θ);
  const sinθ = Math.sin(θ);

  
  
  const xPrime = dx * cosθ + dz * sinθ;
  const zPrime = -dx * sinθ + dz * cosθ;
  return { xPrime, zPrime };
}

/**
 * Generate an 11×11 radar:
 *   - Each cell covers ~6×6 blocks => ±30 blocks in total.
 *   -  at (5,5).
 *   -  in row=0..4, col=5 => "forward direction."
 *   - If multiple entities in same cell => , otherwise .
 *   - Filter out ephemeral entities from EXCLUDED_ENTITIES.
 */
function generateRadarGrid(tank) {
  

  
  const grid = Array.from({ length: GRID_SIZE }, () =>
    Array.from({ length: GRID_SIZE }, () => "")
  );
  

  
  grid[5][5] = "";
  

  
  const tankRot = ((tank.getRotation().y % 360) + 360) % 360;
  const dirStr = getDirectionString(tankRot);
  

  
  for (let row = 0; row < 5; row++) {
    grid[row][5] = "";
  }
  

  
  const rawNearby = tank.dimension.getEntities({
    location: tank.location,
    maxDistance: RADAR_RANGE,
  });
  

  
  const nearby = rawNearby.filter(
    (ent) => !EXCLUDED_ENTITIES.includes(ent.typeId)
  );
  

  
  const scaleFactor = (GRID_SIZE / 2) / RADAR_RANGE;
  

  
  const cellCounts = {};

  
  for (const ent of nearby) {
    if (ent.id === tank.id) continue; 

    const dx = ent.location.x - tank.location.x;
    const dz = ent.location.z - tank.location.z;

    
    const { xPrime, zPrime } = transformToLocal(dx, dz, tankRot);

    
    const gridX = GRID_CENTER + Math.round(xPrime * scaleFactor);
    const gridZ = GRID_CENTER + Math.round(zPrime * scaleFactor);

    
    if (
      gridX >= 0 &&
      gridX < GRID_SIZE &&
      gridZ >= 0 &&
      gridZ < GRID_SIZE
    ) {
      const key = `${gridZ},${gridX}`;
      cellCounts[key] = (cellCounts[key] || 0) + 1;
    }
  }

  
  for (const key in cellCounts) {
    const [rStr, cStr] = key.split(",");
    const row = parseInt(rStr);
    const col = parseInt(cStr);
    const count = cellCounts[key];

    if (grid[row][col] === "" || grid[row][col] === "") {
      if (count === 1) {
        grid[row][col] = "";
        
      } else {
        grid[row][col] = "";
        
      }
    } else {
      
    }
  }

  
  let finalString = "";
  for (let r = 0; r < GRID_SIZE; r++) {
    const rowStr = grid[r].join("");
    finalString += rowStr + "\n\n";
  }

  
  return finalString;
}

/**
 * Displays the radar in an ActionForm:
 * - Title: "军事载具Radar"
 * - Body: bracket placeholders
 * - Buttons: RESCAN => re-call, 返回 => showTankControlUI
 */
export function showArtilleryRadarUI(player, tank) {
  

  const radarText = generateRadarGrid(tank);
  const tankRot = ((tank.getRotation().y % 360) + 360) % 360;
  const dirStr = getDirectionString(tankRot);

  const form = new ActionFormData()
    .title("军事雷达")
    .body(radarText)
    .button("重置", "textures/ui/ttav_buttons/powered_red_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("返回", "textures/ui/ttav_buttons/back_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button")
    .button("锁定", "textures/ui/ttav_buttons/locked_button");

  

  form.show(player).then((res) => {
    
    if (res.canceled || res.selection === 4) {
      
      showArtilleryControlUI(player);
      player.playSound("ttavCameraSwitch", { pitch: 1.0, volume: 1.0 });
      return;
    }
    
    
    showArtilleryRadarUI(player, tank);
    player.playSound("ttavButton1", { pitch: 1.0, volume: 1.0 });
  });
}
