import { world, system, ItemStack } from "@minecraft/server";

const vehicleItems = [
  "pb_plane:plane_air_tractor_1",
  "pb_plane:plane_air_tractor_2",
  "pb_plane:plane_air_tractor_3",
  "pb_plane:plane_airtrike_1",
  "pb_plane:plane_airtrike_2",
  "pb_plane:plane_airtrike_3",
  "pb_plane:plane_biplane_1",
  "pb_plane:plane_biplane_2",
  "pb_plane:plane_biplane_3",
  "pb_plane:plane_skyhawk_1",
  "pb_plane:plane_skyhawk_2",
  "pb_plane:plane_skyhawk_3",
  "pb_plane:plane_cadanair_1",
  "pb_plane:plane_cadanair_2",
  "pb_plane:plane_cadanair_3",
  "pb_plane:plane_cruiser_1",
  "pb_plane:plane_cruiser_2",
  "pb_plane:plane_cruiser_3",
  "pb_plane:plane_ember_120_1",
  "pb_plane:plane_ember_120_2",
  "pb_plane:plane_ember_120_3",
  "pb_plane:plane_magister_1",
  "pb_plane:plane_magister_2",
  "pb_plane:plane_magister_3",
  "pb_plane:plane_gilbert_1",
  "pb_plane:plane_gilbert_2",
  "pb_plane:plane_gilbert_3",
  "pb_plane:plane_glider_1",
  "pb_plane:plane_glider_2",
  "pb_plane:plane_glider_3",
  "pb_plane:plane_galapagos_1",
  "pb_plane:plane_galapagos_2",
  "pb_plane:plane_galapagos_3",
  "pb_plane:plane_northstar_1",
  "pb_plane:plane_northstar_2",
  "pb_plane:plane_northstar_3",
  "pb_plane:plane_wooden_1",
  "pb_plane:plane_wooden_2",
  "pb_plane:plane_wooden_3",
  "pb_plane:plane_lightning_1",
  "pb_plane:plane_lightning_2",
  "pb_plane:plane_lightning_3",
  "pb_plane:plane_passenger_jet_1",
  "pb_plane:plane_passenger_jet_2",
  "pb_plane:plane_passenger_jet_3",
  "pb_plane:plane_ricarde_1",
  "pb_plane:plane_ricarde_2",
  "pb_plane:plane_ricarde_3",
  "pb_plane:plane_seaplane_1",
  "pb_plane:plane_seaplane_2",
  "pb_plane:plane_seaplane_3",
  "pb_plane:plane_marine_1",
  "pb_plane:plane_marine_2",
  "pb_plane:plane_marine_3",
  "pb_plane:plane_triplane_1",
  "pb_plane:plane_triplane_2",
  "pb_plane:plane_triplane_3",
  "pb_plane:plane_vampire_1",
  "pb_plane:plane_vampire_2",
  "pb_plane:plane_vampire_3",
  "pb_plane:heli_cargo_1",
  "pb_plane:heli_cargo_2",
  "pb_plane:heli_cargo_3",
  "pb_plane:heli_leopard_1",
  "pb_plane:heli_leopard_2",
  "pb_plane:heli_leopard_3",
  "pb_plane:heli_remedy_1",
  "pb_plane:heli_remedy_2",
  "pb_plane:heli_remedy_3",
  "pb_plane:drone_passenger_1",
  "pb_plane:drone_passenger_2",
  "pb_plane:drone_passenger_3",
  "pb_plane:blimp_zeppelin_1",
  "pb_plane:blimp_zeppelin_2",
  "pb_plane:blimp_zeppelin_3",
  "pb_plane:speed_boat_1",
  "pb_plane:speed_boat_2",
  "pb_plane:speed_boat_3",
  "pb_plane:car_sports_1",
  "pb_plane:car_sports_2",
  "pb_plane:car_sports_3",
  "pb_plane:car_police_1",
  "pb_plane:car_police_2",
  "pb_plane:car_police_3",
  "pb_plane:car_fire_1",
  "pb_plane:car_fire_2",
  "pb_plane:car_fire_3",
  "pb_plane:car_fire_large_1",
  "pb_plane:car_fire_large_2",
  "pb_plane:car_fire_large_3",
  // 1.1 Update vehicles
  "pb_plane:plane_flying_car_1",
  "pb_plane:plane_flying_car_2",
  "pb_plane:plane_flying_car_3",
  "pb_plane:balloon_1_1",
  "pb_plane:balloon_1_2",
  "pb_plane:balloon_1_3",
  "pb_plane:balloon_2_1",
  "pb_plane:balloon_2_2",
  "pb_plane:balloon_2_3",
  "pb_plane:balloon_3_1",
  "pb_plane:balloon_3_2",
  "pb_plane:balloon_3_3",
  "pb_plane:hover_tuktuk_1",
  "pb_plane:hover_tuktuk_2",
  "pb_plane:hover_tuktuk_3",
  "pb_plane:hover_tukvan_1",
  "pb_plane:hover_tukvan_2",
  "pb_plane:hover_tukvan_3",
  "pb_plane:ufo_1",
  "pb_plane:ufo_2",
  "pb_plane:ufo_3",
  "pb_plane:hover_bike_1",
  "pb_plane:hover_bike_2",
  "pb_plane:hover_bike_3",
  "pb_plane:hover_vespa_1",
  "pb_plane:hover_vespa_2",
  "pb_plane:hover_vespa_3",
];

world.beforeEvents.itemUseOn.subscribe((data) => {
  const player = data.source;
  const item = data.itemStack;

  if (!vehicleItems.includes(item.typeId)) return;

  const customDetails = item.getLore();
  if (!customDetails || customDetails.length === 0) return;

  system.runTimeout(() => {
    const nearbyEntities = player.dimension.getEntities({
      location: player.location,
      maxDistance: 10,
      families: ["pb_plane"],
    });
    nearbyEntities.sort((a, b) => {
      // Calculate the distance between the player and entity a
      const distanceA = Math.sqrt(
        Math.pow(player.location.x - a.location.x, 2) +
          Math.pow(player.location.y - a.location.y, 2) +
          Math.pow(player.location.z - a.location.z, 2)
      );

      // Calculate the distance between the player and entity b
      const distanceB = Math.sqrt(
        Math.pow(player.location.x - b.location.x, 2) +
          Math.pow(player.location.y - b.location.y, 2) +
          Math.pow(player.location.z - b.location.z, 2)
      );

      // Sort in ascending order (closest first)
      return distanceA - distanceB;
    });

    let closestEntity = null;
    for (const entity of nearbyEntities) {
      if (!entity.hasTag("pb_plane_spawn_complete")) {
        closestEntity = entity;
        break; // Exit loop once the first non-tagged entity is found
      }
    }

    if (closestEntity) {
      const colored1 = closestEntity.getProperty("colored_1");
      const colored2 = closestEntity.getProperty("colored_2");

      // Ensure neither "colored_1" nor "colored_2" is set
      if (colored1 || colored2) return;

      customDetails.forEach((detail) => {
        const match = detail.match(
          /Layer (\d+): #?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?/
        ); // Captures RGB and optional alpha
        if (!match) return;

        const [, colorIndex, hexValue, alphaHex] = match;

        // Parse red, green, and blue values from the hex color
        const red = parseFloat(
          (parseInt(hexValue.substring(0, 2), 16) / 255).toFixed(1)
        );
        const green = parseFloat(
          (parseInt(hexValue.substring(2, 4), 16) / 255).toFixed(1)
        );
        const blue = parseFloat(
          (parseInt(hexValue.substring(4, 6), 16) / 255).toFixed(1)
        );

        // Extract alpha from the last two characters of the hex, or use default if not available
        let alpha = 1.0; // Default alpha is 1 (fully opaque)

        if (alphaHex) {
          alpha = parseFloat((parseInt(alphaHex, 16) / 255).toFixed(2)); // Normalize to 0-1 range
        }
        // Set color and alpha properties
        closestEntity.setProperty(`pb_plane:red_${colorIndex}`, red);
        closestEntity.setProperty(`pb_plane:green_${colorIndex}`, green);
        closestEntity.setProperty(`pb_plane:blue_${colorIndex}`, blue);
        closestEntity.setProperty(`pb_plane:alpha_${colorIndex}`, alpha);

        // Update colored_<index> property to true
        closestEntity.setProperty(`pb_plane:colored_${colorIndex}`, true);
        // Tag plane to avoid it being wrongly coloured if a new vehicle spawns nearby
        closestEntity.addTag("pb_plane_spawn_complete");
      });
    }
  });
});

world.afterEvents.entitySpawn.subscribe((data) => {
  const entity = data.entity;
  const familyComp = entity.getComponent("minecraft:type_family");

  if (!familyComp) return;

  const family = entity.getComponent("minecraft:type_family").getTypeFamilies();
  if (family[0] !== "pb_plane") return;
  entity.nameTag = "§r";

  system.runTimeout(() => {
    entity.addTag("pb_plane_spawn_complete");
  }, 20);
});
