import {
  EntityInventoryComponent,
  ItemStack,
  Player,
  system,
  world,
} from "@minecraft/server";
import {
  ActionFormData,
  ActionFormResponse,
  MessageFormData,
} from "@minecraft/server-ui";
import {
  BOOK_IDENTIFIER,
  MAIN_FORM_CONFIG,
  WATCHER_INFO,
  ILLUSIONS_INFO,
  STRUCTURES_INFO,
} from "./guidebookConfig";

const GUIDEBOOK_RECEIVED_KEY = `${BOOK_IDENTIFIER}_received`;

// Pre-build form at module load time to avoid performance spikes
const guidebookForm = new ActionFormData().title({
  rawtext: [{ translate: MAIN_FORM_CONFIG.title }],
});

// Build main body content
const mainBodySections = MAIN_FORM_CONFIG.body;
const mainRawtextElements = [];
if (mainBodySections && mainBodySections.length > 0) {
  for (let i = 0; i < mainBodySections.length; i++) {
    mainRawtextElements.push({ translate: mainBodySections[i] });
    if (i < mainBodySections.length - 1) {
      mainRawtextElements.push({ text: "§r\n\n" });
    }
  }
  mainRawtextElements.push({ text: "§r\n\n" });
}

// Configure guidebook form
guidebookForm.body({ rawtext: mainRawtextElements });
guidebookForm.button({
  rawtext: [{ translate: MAIN_FORM_CONFIG.buttons.watcher }],
});
guidebookForm.button({
  rawtext: [{ translate: MAIN_FORM_CONFIG.buttons.illusions }],
});
guidebookForm.button({
  rawtext: [{ translate: MAIN_FORM_CONFIG.buttons.structures }],
});
guidebookForm.button({
  rawtext: [{ translate: MAIN_FORM_CONFIG.buttons.close }],
});

// Pre-build watcher info form
const watcherInfoForm = new ActionFormData()
  .title({ rawtext: [{ translate: WATCHER_INFO.title }] })
  .body({ rawtext: [{ translate: WATCHER_INFO.description }, { text: "§r\n\n" }] });

watcherInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.back" }],
});
watcherInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.close" }],
});

// Pre-build illusions info form
const illusionsInfoForm = new ActionFormData()
  .title({ rawtext: [{ translate: ILLUSIONS_INFO.title }] })
  .body({ rawtext: [{ translate: ILLUSIONS_INFO.description }, { text: "§r\n\n" }] });

illusionsInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.back" }],
});
illusionsInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.close" }],
});

// Pre-build structures info form
const structuresInfoForm = new ActionFormData()
  .title({ rawtext: [{ translate: STRUCTURES_INFO.title }] })
  .body({ rawtext: [{ translate: STRUCTURES_INFO.description }, { text: "§r\n\n" }] });

structuresInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.back" }],
});
structuresInfoForm.button({
  rawtext: [{ translate: "mythicus_tw:ui.button.close" }],
});

export async function showGuidebook(player) {
  player.playSound("item.book.page_turn", { volume: 0.6, pitch: 1.0 });

  const response = await guidebookForm.show(player);

  if (response.canceled) return;

  switch (response.selection) {
    case 0:
      showWatcherInfo(player);
      break;
    case 1:
      showIllusionsInfo(player);
      break;
    case 2:
      showStructuresInfo(player);
      break;
    case 3:
      break;
  }
}

async function showWatcherInfo(player) {
  const response = await watcherInfoForm.show(player);
  player.playSound("item.book.page_turn", { volume: 0.6, pitch: 1.0 });

  if (!response.canceled && response.selection === 0) {
    showGuidebook(player);
  }
}

async function showIllusionsInfo(player) {
  const response = await illusionsInfoForm.show(player);
  player.playSound("item.book.page_turn", { volume: 0.6, pitch: 1.0 });

  if (!response.canceled && response.selection === 0) {
    showGuidebook(player);
  }
}

async function showStructuresInfo(player) {
  const response = await structuresInfoForm.show(player);
  player.playSound("item.book.page_turn", { volume: 0.6, pitch: 1.0 });

  if (!response.canceled && response.selection === 0) {
    showGuidebook(player);
  }
}

world.afterEvents.itemUse.subscribe((event) => {
  const { source: player, itemStack } = event;
  if (itemStack.typeId === BOOK_IDENTIFIER) {
    showGuidebook(player);
  }
});

world.afterEvents.itemUseOn.subscribe((event) => {
  const { source: player, itemStack } = event;
  if (itemStack.typeId === BOOK_IDENTIFIER) {
    showGuidebook(player);
  }
});

export function hasReceivedGuidebook(player) {
  const receivedProperty = player.getDynamicProperty(GUIDEBOOK_RECEIVED_KEY);
  return receivedProperty === true;
}

export function giveGuidebook(player) {
  if (!hasReceivedGuidebook(player)) {
    const guidebook = new ItemStack(BOOK_IDENTIFIER, 1);

    const inventory = player.getComponent(EntityInventoryComponent.componentId);
    if (inventory && inventory.container) {
      inventory.container.addItem(guidebook);

      player.setDynamicProperty(GUIDEBOOK_RECEIVED_KEY, true);
    }
  }
}
