import { world, ItemStack, system, GameMode } from "@minecraft/server";
import { updateBlock } from "../utils/block";
import { consumeEquipped } from "../utils/item";

const Utils = {
  getPlayerEquipment(player) {
    return player.getComponent("equippable");
  },
  getSelectedItem(player) {
    const equip = this.getPlayerEquipment(player);
    return equip ? equip.getEquipment("Mainhand") : null;
  },
  consumeItem(player, item) {
    if (player.getGameMode() === GameMode.creative) return;
    const equip = this.getPlayerEquipment(player);
    consumeEquipped(equip, item);
  },
  setBlockState(block, stateName, value) {
    updateBlock(block, { [stateName]: value });
  },
  giveItem(player, id, amount = 1) {
    player.getComponent("inventory").container.addItem(new ItemStack(id, amount));
  },
  playSound(block, sound) {
    try {
      block.dimension.playSound(sound, block.location);
    } catch (e) {
      console.warn("playSound falhou:", sound, e);
    }
  },
  spawnParticle(block, particle) {
    const loc = block.location;
    try {
      block.dimension.spawnParticle(particle, {
        x: loc.x + 0.5,
        y: loc.y + 1,
        z: loc.z + 0.5
      });
    } catch (e) {}
  }
};

const ticksToMs = ticks => Math.round(ticks * 50);

const ingredientTickRanges = {
  4: [840, 900],     // beer
  5: [2700, 3150],   // wine
  6: [850, 900],     // mozzarella
  7: [2650, 2700],   // camembert
  8: [3100, 3150],   // cheddar
  9: [800, 950]      // mead
};

function randomBetween(min, max) {
  if (min === max) return min;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function startProcessing(block, ingredient) {
  Utils.setBlockState(block, "peach:progress", 1);

  const range = ingredientTickRanges[ingredient];
  if (!range) {
    const ms = ticksToMs(900);
    system.runTimeout(() => {
      Utils.setBlockState(block, "peach:progress", 2);
      Utils.playSound(block, "note.bell");
      Utils.spawnParticle(block, "minecraft:crop_growth_emitter");
    }, ms);
    return;
  }

  const ticks = randomBetween(range[0], range[1]);
  const ms = ticksToMs(ticks);

  system.runTimeout(() => {
    Utils.setBlockState(block, "peach:progress", 2);
    Utils.playSound(block, "note.bell");
    Utils.spawnParticle(block, "minecraft:crop_growth_emitter");
  }, ms);
}

world.beforeEvents.worldInitialize.subscribe(pch => {
  pch.blockComponentRegistry.registerCustomComponent("peach:fermenter_logic", {
    onPlayerInteract: e => {
      const { player, block } = e;
      const selectedItem = Utils.getSelectedItem(player);

      const rawIngredient = block.permutation.getState("peach:ingredients");
      const rawProgress = block.permutation.getState("peach:progress");
      const ingredient = Number(rawIngredient);
      const progress = Number(rawProgress);

      if (progress === 2) {
        if (ingredient === 4 && selectedItem?.typeId === "minecraft:barrel") {
          Utils.consumeItem(player, selectedItem);
          Utils.giveItem(player, "peach:barrel_beer");
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "bucket.fill_water");
          return;
        }

        if (ingredient === 5 && selectedItem?.typeId === "minecraft:barrel") {
          Utils.consumeItem(player, selectedItem);
          Utils.giveItem(player, "peach:barrel_wine");
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "bucket.fill_water");
          return;
        }

        if (ingredient === 6) {
          Utils.giveItem(player, "peach:mozzarella", 3);
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "use.honey_block");
          return;
        }

        if (ingredient === 7) {
          Utils.giveItem(player, "peach:camembert", 1);
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "use.honey_block");
          return;
        }

        if (ingredient === 8) {
          Utils.giveItem(player, "peach:cheddar", 3);
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "use.honey_block");
          return;
        }

        if (ingredient === 9 && selectedItem?.typeId === "minecraft:barrel") {
          Utils.consumeItem(player, selectedItem);
          Utils.giveItem(player, "peach:barrel_mead");
          Utils.setBlockState(block, "peach:ingredients", 0);
          Utils.setBlockState(block, "peach:progress", 0);
          Utils.playSound(block, "bucket.fill_water");
          return;
        }
      }

      if (ingredient === 0) {
        if (selectedItem?.typeId === "minecraft:milk_bucket") {
          Utils.consumeItem(player, selectedItem);
          Utils.giveItem(player, "minecraft:bucket");
          Utils.setBlockState(block, "peach:ingredients", 1);
          Utils.playSound(block, "note.bit");
          return;
        }

        if (selectedItem?.typeId === "minecraft:brown_mushroom") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 2);
          Utils.playSound(block, "note.bit");
          return;
        }

        if (selectedItem?.typeId === "minecraft:honey_block" || selectedItem?.typeId === "peach:honey_block") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 9);
          Utils.playSound(block, "note.bit");
          return;
        }
      }

      if (ingredient === 2) {
        if (selectedItem?.typeId === "minecraft:wheat") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 4);
          startProcessing(block, 4);
          Utils.playSound(block, "note.bit");
          return;
        }
        if (selectedItem?.typeId === "peach:grape" || selectedItem?.typeId === "minecraft:glow_berries") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 5);
          startProcessing(block, 5);
          Utils.playSound(block, "note.bit");
          return;
        }
      }

      if (ingredient === 1) {
        if (selectedItem?.typeId === "peach:lemon" || selectedItem?.typeId === "minecraft:lemon") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 3);
          Utils.playSound(block, "note.bit");
          return;
        }
      }

      if (ingredient === 9) {
        if (selectedItem?.typeId === "minecraft:water_bucket") {
          Utils.consumeItem(player, selectedItem);
          Utils.giveItem(player, "minecraft:bucket");
          startProcessing(block, 9);
          Utils.playSound(block, "note.bit");
          return;
        }
      }

      if (ingredient === 3) {
        if (selectedItem?.typeId === "peach:salt" || selectedItem?.typeId === "minecraft:salt") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 6);
          startProcessing(block, 6);
          Utils.playSound(block, "note.bit");
          return;
        }
        if (selectedItem?.typeId === "peach:turmenic" || selectedItem?.typeId === "peach:turmeric" || selectedItem?.typeId === "minecraft:turmeric") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 8);
          startProcessing(block, 8);
          Utils.playSound(block, "note.bit");
          return;
        }
        if (selectedItem?.typeId === "minecraft:red_mushroom") {
          Utils.consumeItem(player, selectedItem);
          Utils.setBlockState(block, "peach:ingredients", 7);
          startProcessing(block, 7);
          Utils.playSound(block, "note.bit");
          return;
        }
      }
    }
  });
});
