import PrismRPGActorSheet from "./base-actor-sheet.mjs"
import PrismRPGRoll from "../../documents/roll.mjs"

export default class PrismRPGMonsterSheet extends PrismRPGActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["monster"],
    position: {
      width: 1060,
      height: 780,
    },
    window: {
      contentClasses: ["monster-content"],
    },
    actions: {
      rangedAttackDefense: PrismRPGMonsterSheet.#onRangedAttackDefense,
      rollInitiative: PrismRPGMonsterSheet.#onRollInitiative,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-prism-rpg/templates/monster-main.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    combat: {
      template: "systems/fvtt-prism-rpg/templates/monster-combat.hbs",
    },
    biography: {
      template: "systems/fvtt-prism-rpg/templates/monster-biography.hbs",
    },
  }

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

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    let tabs = {
      combat: { id: "combat", group: "sheet", icon: "fa-solid fa-swords", label: "PRISMRPG.Label.combat" },
      biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "PRISMRPG.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 "combat":
        context.tab = context.tabs.combat
        context.weapons = doc.itemTypes.weapon
        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
  }

  // #region Drag-and-Drop Workflow

  /**
   * Callback actions which occur when a dragged element is dropped on a target.
   * @param {DragEvent} event       The originating DragEvent
   * @protected
   */
  async _onDrop(event) {
    if (!this.isEditable || !this.isEditMode) return
    const data = TextEditor.getDragEventData(event)

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

  static async #onRangedAttackDefense(event, target) {
    const hasTarget = false

    let roll = await PrismRPGRoll.promptRangedDefense({
      actorId: this.actor.id,
      actorName: this.actor.name,
      actorImage: this.actor.img,
    })
    if (!roll) return null

    await roll.toMessage({}, { rollMode: roll.options.rollMode })
  }

  static async #onRollInitiative(event, target) {
    await this.document.system.rollInitiative(event, target)
  }

  getBestWeaponClassSkill(skills, rollType, multiplier = 1.0) {
    let maxValue = 0
    let goodSkill = skills[0]
    for (let s of skills) {
      if (rollType === "weapon-attack") {
        if (s.system.weaponBonus.attack > maxValue) {
          maxValue = Number(s.system.weaponBonus.attack)
          goodSkill = s
        }
      }
      if (rollType === "weapon-defense") {
        if (s.system.weaponBonus.defense > maxValue) {
          maxValue = Number(s.system.weaponBonus.defense)
          goodSkill = s
        }
      }
      if (rollType.includes("weapon-damage")) {
        if (s.system.weaponBonus.damage > maxValue) {
          maxValue = Number(s.system.weaponBonus.damage)
          goodSkill = s
        }
      }
    }
    goodSkill.weaponSkillModifier = maxValue * multiplier
    return goodSkill
  }

  /**
   * 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) {
    if (this.isEditMode) return
    // Use closest to find the rollable element in case user clicked on a child
    const rollableElement = event.target.closest('.rollable') || event.target
    const rollType = rollableElement.dataset.rollType
    let rollKey = rollableElement.dataset.rollKey
    let rollDice = rollableElement.dataset?.rollDice || "0"
    this.actor.system.prepareMonsterRoll(rollType, rollKey, rollDice)
  }
}
