import { system, world } from "@minecraft/server";
import { ItemInventoryContents } from "../utilities.js";
import { replaceableBlocks, waterloggableBlocks } from "./bucketList.js";

export function bottomlessBucket(player, item, event) {
  const contents =
    new ItemInventoryContents(item).getContainer()?.content ?? [];

  const hasExtra = contents.some(
    (stack) => stack?.typeId === "pb_gat:orb_extra"
  );
  const hasLava = contents.some((stack) => stack?.typeId === "pb_gat:orb_lava");
  const hasSponge = contents.some(
    (stack) => stack?.typeId === "pb_gat:orb_sponge"
  );

  const clickedBlock = event.block;
  const face = event.blockFace;
  const clickedLoc = clickedBlock.location;
  const dimension = player.dimension;
  const isNether = dimension.id === "minecraft:nether";

  const clickedType = clickedBlock.typeId;

  let targetLocations = [getOffsetLocation(clickedLoc, face)];

  if (waterloggableBlocks.includes(clickedType)) {
    targetLocations = [{ ...clickedLoc }];
  }

  if (hasExtra) {
    const base = targetLocations[0];
    targetLocations = [];
    for (let dx = -1; dx <= 1; dx++) {
      for (let dz = -1; dz <= 1; dz++) {
        targetLocations.push({ x: base.x + dx, y: base.y, z: base.z + dz });
      }
    }
  }

  const isPlacingWater = !hasLava && !hasSponge;
  if (isPlacingWater && isNether) {
    dimension.runCommand(
      `particle minecraft:large_smoke ${clickedLoc.x} ${clickedLoc.y + 1} ${
        clickedLoc.z
      }`
    );
    dimension.runCommand(
      `playsound random.fizz @a[r=6] ${clickedLoc.x} ${clickedLoc.y + 1} ${
        clickedLoc.z
      }`
    );
    return;
  }

  system.run(() => {
    for (const loc of targetLocations) {
      const block = dimension.getBlock(loc);
      if (!block) continue;

      const type = block.typeId;
      const placingLava = hasLava && !hasSponge;
      const removingLiquid = hasSponge;
      const placingWater = !hasLava && !hasSponge;

      // Handle removal logic
      if (removingLiquid) {
        const isWater =
          type === "minecraft:water" || type === "minecraft:flowing_water";
        const isLava =
          type === "minecraft:lava" || type === "minecraft:flowing_lava";

        // 1. Remove matching liquid
        if (hasLava && isLava) {
          player.playSound("bucket.fill_lava", {
            pitch: 1,
            volume: 1,
            location: block.location,
          });
          dimension.runCommand(
            `setblock ${loc.x} ${loc.y} ${loc.z} air replace`
          );
        }
        if (!hasLava && isWater) {
          player.playSound("bucket.fill_water", {
            pitch: 1,
            volume: 1,
            location: block.location,
          });
          dimension.runCommand(
            `setblock ${loc.x} ${loc.y} ${loc.z} air replace`
          );
        }

        // 2. Remove waterlogged state ONLY if water, not when using lava mode
        if (!hasLava && waterloggableBlocks.includes(type)) {
          try {
            if (typeof block.setWaterlogged === "function") {
              block.setWaterlogged(false);
            }
          } catch (e) {}
        }

        continue;
      }

      // Place lava
      if (placingLava) {
        if (replaceableBlocks.includes(type) || block.isAir) {
          dimension.runCommand(
            `setblock ${loc.x} ${loc.y} ${loc.z} flowing_lava`
          );
        }
        player.playSound("bucket.empty_lava", {
          pitch: 1,
          volume: 1,
          location: block.location,
        });
        continue;
      }

      // Place water or waterlog
      if (waterloggableBlocks.includes(type)) {
        try {
          if (typeof block.setWaterlogged === "function") {
            block.setWaterlogged(true);
            continue;
          }
        } catch (e) {}
      }

      if (replaceableBlocks.includes(type)) {
        dimension.runCommand(
          `setblock ${loc.x} ${loc.y} ${loc.z} flowing_water destroy`
        );
        player.playSound("bucket.empty_water", {
          pitch: 1,
          volume: 1,
          location: block.location,
        });
      } else if (type === "minecraft:water") {
        block.setType("minecraft:flowing_water");
        player.playSound("bucket.empty_water", {
          pitch: 1,
          volume: 1,
          location: block.location,
        });
      } else if (block.isAir) {
        block.setType("minecraft:flowing_water");
        player.playSound("bucket.empty_water", {
          pitch: 1,
          volume: 1,
          location: block.location,
        });
      }
    }
  });
}

function getOffsetLocation(loc, face) {
  const offsets = {
    up: { x: 0, y: 1, z: 0 },
    down: { x: 0, y: -1, z: 0 },
    north: { x: 0, y: 0, z: -1 },
    south: { x: 0, y: 0, z: 1 },
    west: { x: -1, y: 0, z: 0 },
    east: { x: 1, y: 0, z: 0 },
  };
  const offset = offsets[face.toLowerCase()] ?? { x: 0, y: 0, z: 0 };
  return {
    x: loc.x + offset.x,
    y: loc.y + offset.y,
    z: loc.z + offset.z,
  };
}
