import HamalronActorSheet from "./base-actor-sheet.mjs"

export default class HamalronEnemySheet extends HamalronActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["enemy"],
    position: {
      width: 860,
      height: 620,
    },
    window: {
      contentClasses: ["enemy-content"],
    },
    actions: {
      createEquipment: HamalronEnemySheet.#onCreateEquipment,
      createWeapon: HamalronEnemySheet.#onCreateWeapon,
      createSortilege: HamalronEnemySheet.#onCreateSortilege,
    }

  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-hamalron/templates/enemy-main.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    traits: {
      template: "systems/fvtt-hamalron/templates/enemy-trait.hbs",
    },
    biography: {
      template: "systems/fvtt-hamalron/templates/enemy-biography.hbs",
    },
  }

  /** @override */
  tabGroups = {
    sheet: "traits",
  }


  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    const tabs = {
      traits: { id: "traits", group: "sheet", icon: "fa-solid fa-shapes", label: "HAMALRON.Label.traits" },
      biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "HAMALRON.Label.biography" },
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()

    return context
  }

  /** @override */
  async _preparePartContext(partId, context) {
    const doc = this.document
    switch (partId) {
      case "main":
        break
      case "traits":
        context.tab = context.tabs.traits
        context.traits = doc.itemTypes.competence || []
        context.traits.sort((a, b) => a.name.localeCompare(b.name))
        context.weapons = doc.itemTypes.arme || []
        context.weapons.sort((a, b) => a.name.localeCompare(b.name))
        context.sortileges = doc.itemTypes.sortilege || []
        context.sortileges.sort((a, b) => a.name.localeCompare(b.name))
        context.equipments = doc.itemTypes.equipement || []
        context.equipments.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "biography":
        context.tab = context.tabs.biography
        context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.description, { async: true })
        context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.notes, { async: true })
        break
    }
    return context
  }

  static #onCreateEquipment(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HAMALRON.Label.newEquipment"), type: "equipement" }])
  }

  static #onCreateSortilege(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HAMALRON.Label.newSortilege"), type: "sortilege" }])
  }

  static #onCreateWeapon(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HAMALRON.Label.newWeapon"), type: "arme" }])
  }


  /**
   * Handles the roll action triggered by user interaction.
   *
   * @param {PointerEvent} event The event object representing the user interaction.
   * @param {HTMLElement} target The target element that triggered the roll.
   *
   * @returns {Promise<void>} A promise that resolves when the roll action is complete.
   *
   * @throws {Error} Throws an error if the roll type is not recognized.
   *
   * @description This method checks the current mode (edit or not) and determines the type of roll
   * (save, resource, or damage) based on the target element's data attributes. It retrieves the
   * corresponding value from the document's system and performs the roll.
   */
  async _onRoll(event, target) {
    const rollType = $(event.currentTarget).data("roll-type")
    let item
    switch (rollType) {
      case "stat":
        {
          let statId = $(event.currentTarget).data("stat-id");
          item = this.actor.system?.stats?.[statId];
          if (item) await this.document.system.roll(rollType, item)
        }
        break
      case "weapon":
      case "damage":
        {
          let li = $(event.currentTarget).parents(".item");
          item = this.actor.items.get(li.data("item-id"));
          if (item) await this.document.system.roll(rollType, item)
        }
        break
      default:
        throw new Error(`Unknown roll type ${rollType}`)
    }
  }

  async _onDrop(event) {
    if (!this.isEditable || !this.isEditMode) return
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)

    // Handle different data types
    switch (data.type) {
      case "Item":
        const item = await fromUuid(data.uuid)
        return super._onDropItem(item)
    }
  }
}
