import { system } from "@minecraft/server";
import { ItemInventoryContents } from "../utilities.js";
import { highlightBlock } from "../blockHighlight.js";

const stoneMap = {
  // STONE TYPES
  // Stone
  "minecraft:stone": "minecraft:andesite",
  "minecraft:andesite": "minecraft:diorite",
  "minecraft:diorite": "minecraft:granite",
  "minecraft:granite": "minecraft:stone",
  // Deepslate and Geode
  "minecraft:deepslate": "minecraft:tuff",
  "minecraft:tuff": "minecraft:calcite",
  "minecraft:calcite": "minecraft:deepslate",
};

const treeMap = {
  // LOG TYPES
  "minecraft:oak_log": "minecraft:spruce_log",
  "minecraft:spruce_log": "minecraft:birch_log",
  "minecraft:birch_log": "minecraft:jungle_log",
  "minecraft:jungle_log": "minecraft:acacia_log",
  "minecraft:acacia_log": "minecraft:dark_oak_log",
  "minecraft:dark_oak_log": "minecraft:mangrove_log",
  "minecraft:mangrove_log": "minecraft:cherry_log",
  "minecraft:cherry_log": "minecraft:pale_oak_log",
  "minecraft:pale_oak_log": "minecraft:oak_log",
  "minecraft:crimson_stem": "minecraft:warped_stem",
  "minecraft:warped_stem": "minecraft:crimson_stem",
  // STRIPPED LOG TYPES
  "minecraft:stripped_oak_log": "minecraft:stripped_spruce_log",
  "minecraft:stripped_spruce_log": "minecraft:stripped_birch_log",
  "minecraft:stripped_birch_log": "minecraft:stripped_jungle_log",
  "minecraft:stripped_jungle_log": "minecraft:stripped_acacia_log",
  "minecraft:stripped_acacia_log": "minecraft:stripped_dark_oak_log",
  "minecraft:stripped_dark_oak_log": "minecraft:stripped_mangrove_log",
  "minecraft:stripped_mangrove_log": "minecraft:stripped_cherry_log",
  "minecraft:stripped_cherry_log": "minecraft:stripped_pale_oak_log",
  "minecraft:stripped_pale_oak_log": "minecraft:stripped_oak_log",
  "minecraft:stripped_crimson_stem": "minecraft:stripped_warped_stem",
  "minecraft:stripped_warped_stem": "minecraft:stripped_crimson_stem",
  // WOOD TYPES
  "minecraft:oak_wood": "minecraft:spruce_wood",
  "minecraft:spruce_wood": "minecraft:birch_wood",
  "minecraft:birch_wood": "minecraft:jungle_wood",
  "minecraft:jungle_wood": "minecraft:acacia_wood",
  "minecraft:acacia_wood": "minecraft:dark_oak_wood",
  "minecraft:dark_oak_wood": "minecraft:mangrove_wood",
  "minecraft:mangrove_wood": "minecraft:cherry_wood",
  "minecraft:cherry_wood": "minecraft:pale_oak_wood",
  "minecraft:pale_oak_wood": "minecraft:oak_wood",
  "minecraft:crimson_hyphae": "minecraft:warped_hyphae",
  "minecraft:warped_hyphae": "minecraft:crimson_hyphae",
  // STRIPPED WOOD TYPES
  "minecraft:stripped_oak_wood": "minecraft:stripped_spruce_wood",
  "minecraft:stripped_spruce_wood": "minecraft:stripped_birch_wood",
  "minecraft:stripped_birch_wood": "minecraft:stripped_jungle_wood",
  "minecraft:stripped_jungle_wood": "minecraft:stripped_acacia_wood",
  "minecraft:stripped_acacia_wood": "minecraft:stripped_dark_oak_wood",
  "minecraft:stripped_dark_oak_wood": "minecraft:stripped_mangrove_wood",
  "minecraft:stripped_mangrove_wood": "minecraft:stripped_cherry_wood",
  "minecraft:stripped_cherry_wood": "minecraft:stripped_pale_oak_wood",
  "minecraft:stripped_pale_oak_wood": "minecraft:stripped_oak_wood",
  "minecraft:stripped_crimson_hyphae": "minecraft:stripped_warped_hyphae",
  "minecraft:stripped_warped_hyphae": "minecraft:stripped_crimson_hyphae",
  // PLANK TYPES
  "minecraft:oak_planks": "minecraft:spruce_planks",
  "minecraft:spruce_planks": "minecraft:birch_planks",
  "minecraft:birch_planks": "minecraft:jungle_planks",
  "minecraft:jungle_planks": "minecraft:acacia_planks",
  "minecraft:acacia_planks": "minecraft:dark_oak_planks",
  "minecraft:dark_oak_planks": "minecraft:mangrove_planks",
  "minecraft:mangrove_planks": "minecraft:cherry_planks",
  "minecraft:cherry_planks": "minecraft:pale_oak_planks",
  "minecraft:pale_oak_planks": "minecraft:oak_planks",
  "minecraft:crimson_planks": "minecraft:warped_planks",
  "minecraft:warped_planks": "minecraft:crimson_planks",
  // LEAF TYPES
  "minecraft:oak_leaves": "minecraft:spruce_leaves",
  "minecraft:spruce_leaves": "minecraft:birch_leaves",
  "minecraft:birch_leaves": "minecraft:jungle_leaves",
  "minecraft:jungle_leaves": "minecraft:acacia_leaves",
  "minecraft:acacia_leaves": "minecraft:dark_oak_leaves",
  "minecraft:dark_oak_leaves": "minecraft:mangrove_leaves",
  "minecraft:mangrove_leaves": "minecraft:cherry_leaves",
  "minecraft:cherry_leaves": "minecraft:pale_oak_leaves",
  "minecraft:pale_oak_leaves": "minecraft:azalea_leaves",
  "minecraft:azalea_leaves": "minecraft:azalea_leaves_flowered",
  "minecraft:azalea_leaves_flowered": "minecraft:oak_leaves",
  "minecraft:nether_wart_block": "minecraft:warped_wart_block",
  "minecraft:warped_wart_block": "minecraft:nether_wart_block",
  // SAPLING TYPES
  "minecraft:oak_sapling": "minecraft:spruce_sapling",
  "minecraft:spruce_sapling": "minecraft:birch_sapling",
  "minecraft:birch_sapling": "minecraft:jungle_sapling",
  "minecraft:jungle_sapling": "minecraft:acacia_sapling",
  "minecraft:acacia_sapling": "minecraft:dark_oak_sapling",
  "minecraft:dark_oak_sapling": "minecraft:mangrove_propagule",
  "minecraft:mangrove_propagule": "minecraft:cherry_sapling",
  "minecraft:cherry_sapling": "minecraft:pale_oak_sapling",
  "minecraft:pale_oak_sapling": "minecraft:azalea",
  "minecraft:azalea": "minecraft:flowering_azalea",
  "minecraft:flowering_azalea": "minecraft:bamboo_sapling",
  "minecraft:bamboo_sapling": "minecraft:oak_sapling",
};
const dirtMap = {
  // DIRT TYPES
  "minecraft:dirt": "minecraft:coarse_dirt",
  "minecraft:coarse_dirt": "minecraft:dirt_with_roots",
  "minecraft:dirt_with_roots": "minecraft:gravel",
  "minecraft:gravel": "minecraft:sand",
  "minecraft:sand": "minecraft:red_sand",
  "minecraft:red_sand": "minecraft:clay",
  "minecraft:clay": "minecraft:mud",
  "minecraft:mud": "minecraft:dirt",
};
const grassMap = {
  // GRASS TYPES
  "minecraft:grass_block": "minecraft:podzol",
  "minecraft:podzol": "minecraft:mycelium",
  "minecraft:mycelium": "minecraft:grass_block",
};

// Reverse maps
function createReverseMap(map) {
  return Object.entries(map).reduce((acc, [key, value]) => {
    acc[value] = key;
    return acc;
  }, {});
}

const reverseStoneMap = createReverseMap(stoneMap);
const reverseTreeMap = createReverseMap(treeMap);
const reverseDirtMap = createReverseMap(dirtMap);
const reverseGrassMap = createReverseMap(grassMap);

export function handleMirror(player, item, block) {
  system.run(() => {
    if (!item || !block) return;

    const contents =
      new ItemInventoryContents(item).getContainer()?.content ?? [];

    const hasTree = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_tree"
    );
    const hasDirt = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_dirt"
    );
    const hasGrass = contents.some(
      (stack) => stack?.typeId === "pb_gat:orb_grass"
    );

    // Select correct map
    let map = stoneMap;
    let reverseMap = reverseStoneMap;
    if (hasTree) {
      map = treeMap;
      reverseMap = reverseTreeMap;
    } else if (hasDirt) {
      map = dirtMap;
      reverseMap = reverseDirtMap;
    } else if (hasGrass) {
      map = grassMap;
      reverseMap = reverseGrassMap;
    }

    const currentBlockId = block.typeId;
    const isSneaking = player.isSneaking;
    const newType = isSneaking
      ? reverseMap[currentBlockId]
      : map[currentBlockId];

    if (!newType) {
      player.sendMessage(
        "§4->§r You cannot transform this block, you may need a Mirror Disk installed."
      );
      return;
    }

    // Preserve applicable states before changing type
    const pillarAxisState = block.permutation.getState("pillar_axis");
    const persistentState = block.permutation.getState("persistent_bit");

    // Change block type
    system.runTimeout(() => {
      block.setType(newType);
    }, 10);
    highlightBlock(block, "white", "mirror");
    player.playSound("mob.evocation_illager.prepare_summon", {
      pitch: 1.8,
      volume: 0.7,
      location: player.location,
    });

    // Re-fetch permutation after changing type
    let newPermutation = block.permutation;

    // Reapply each state individually (in try/catch where needed)
    if (pillarAxisState !== undefined) {
      try {
        newPermutation = newPermutation.withState(
          "pillar_axis",
          pillarAxisState
        );
        block.setPermutation(newPermutation);
      } catch {}
    }

    if (persistentState !== undefined) {
      try {
        newPermutation = newPermutation.withState(
          "persistent_bit",
          persistentState
        );
        block.setPermutation(newPermutation);
      } catch {}
    }
  });
}
