import LethalFantasyActorSheet from "./base-actor-sheet.mjs"
import LethalFantasyRoll from "../../documents/roll.mjs"

export default class LethalFantasyCharacterSheet extends LethalFantasyActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["character"],
    position: {
      width: 972,
      height: 780,
    },
    window: {
      contentClasses: ["character-content"],
    },
    actions: {
      createEquipment: LethalFantasyCharacterSheet.#onCreateEquipment,
      rangedAttackDefense: LethalFantasyCharacterSheet.#onRangedAttackDefense,
      rollInitiative: LethalFantasyCharacterSheet.#onRollInitiative,
      armorHitPointsPlus: LethalFantasyCharacterSheet.#onArmorHitPointsPlus,
      armorHitPointsMinus: LethalFantasyCharacterSheet.#onArmorHitPointsMinus,
      divinityPointsPlus: LethalFantasyCharacterSheet.#onDivinityPointsPlus,
      divinityPointsMinus: LethalFantasyCharacterSheet.#onDivinityPointsMinus,
      aetherPointsPlus: LethalFantasyCharacterSheet.#onAetherPointsPlus,
      aetherPointsMinus: LethalFantasyCharacterSheet.#onAetherPointsMinus,
      rollSpellDamage: LethalFantasyCharacterSheet.#onRollSpellDamage,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-lethal-fantasy/templates/character-main.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    skills: {
      template: "systems/fvtt-lethal-fantasy/templates/character-skills.hbs",
    },
    combat: {
      template: "systems/fvtt-lethal-fantasy/templates/character-combat.hbs",
    },
    equipment: {
      template: "systems/fvtt-lethal-fantasy/templates/character-equipment.hbs",
    },
    spells: {
      template: "systems/fvtt-lethal-fantasy/templates/character-spells.hbs",
    },
    miracles: {
      template: "systems/fvtt-lethal-fantasy/templates/character-miracles.hbs",
    },
    biography: {
      template: "systems/fvtt-lethal-fantasy/templates/character-biography.hbs",
    },
  }

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

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    let tabs = {
      skills: { id: "skills", group: "sheet", icon: "fa-solid fa-shapes", label: "LETHALFANTASY.Label.skills" },
      combat: { id: "combat", group: "sheet", icon: "fa-solid fa-swords", label: "LETHALFANTASY.Label.combat" },
      equipment: { id: "equipment", group: "sheet", icon: "fa-solid fa-backpack", label: "LETHALFANTASY.Label.equipment" },
      biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "LETHALFANTASY.Label.biography" },
    }
    if (this.actor.system.biodata.magicUser) {
      tabs.spells = { id: "spells", group: "sheet", icon: "fa-solid fa-wand-magic-sparkles", label: "LETHALFANTASY.Label.spells" }
    }
    if (this.actor.system.biodata.clericUser) {
      tabs.miracles = { id: "miracles", group: "sheet", icon: "fa-solid fa-hands-praying", label: "LETHALFANTASY.Label.miracles" }
    }
    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":
        context.armorDR = this.actor.getArmorDR()
        context.damageReduction = this.actor.computeDamageReduction()
        context.damageReductionShield = this.actor.getShieldDR()
        break
      case "skills": {
        context.tab = context.tabs.skills
        context.skills = doc.itemTypes.skill
        // Organiser les skills par catégorie
        const categories = ['layperson', 'professional', 'weapon', 'armor', 'resist']
        context.skillsByCategory = categories.map(cat => {
          return {
            category: cat,
            label: `LETHALFANTASY.Skill.Category.${cat}`,
            skills: context.skills.filter(s => s.system.category === cat)
          }
        }).filter(catData => catData.skills.length > 0)
        context.gifts = doc.itemTypes.gift
        context.vulnerabilities = doc.itemTypes.vulnerability
        break
      }
      case "spells":
        context.tab = context.tabs.spells
        context.spells = doc.itemTypes.spell
        context.hasSpells = context.spells.length > 0
        break
      case "miracles":
        context.tab = context.tabs.miracles
        context.miracles = doc.itemTypes.miracle
        context.hasMiracles = context.miracles.length > 0
        break
      case "combat":
        context.tab = context.tabs.combat
        context.weapons = doc.itemTypes.weapon
        context.armors = doc.itemTypes.armor
        context.shields = doc.itemTypes.shield
        break
      case "equipment":
        context.tab = context.tabs.equipment
        context.equipments = doc.itemTypes.equipment
        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 = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)

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

  static async #onRangedAttackDefense(event, target) {
    // Future use : const hasTarget = false

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

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

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

  static async #onArmorHitPointsPlus(event, target) {
    let armorHP = this.actor.system.combat.armorHitPoints
    armorHP += 1
    await this.actor.update({ "system.combat.armorHitPoints": armorHP })
  }

  static async #onArmorHitPointsMinus(event, target) {
    let armorHP = this.actor.system.combat.armorHitPoints
    armorHP -= 1
    await this.actor.update({ "system.combat.armorHitPoints": Math.max(armorHP, 0) })
  }

  static async #onDivinityPointsPlus(event, target) {
    let points = this.actor.system.divinityPoints.value
    points += 1
    points = Math.min(points, this.actor.system.divinityPoints.max)
    await this.actor.update({ "system.divinityPoints.value": points })
  }

  static async #onDivinityPointsMinus(event, target) {
    let points = this.actor.system.divinityPoints.value
    points -= 1
    points = Math.max(points, 0)
    await this.actor.update({ "system.divinityPoints.value": points })
  }

  static async #onAetherPointsPlus(event, target) {
    let points = this.actor.system.aetherPoints.value
    points += 1
    points = Math.min(points, this.actor.system.aetherPoints.max)
    await this.actor.update({ "system.aetherPoints.value": points })
  }

  static async #onAetherPointsMinus(event, target) {
    let points = this.actor.system.aetherPoints.value
    points -= 1
    points = Math.max(points, 0)
    await this.actor.update({ "system.aetherPoints.value": points })
  }

  /**
   * Handles spell damage roll from the spell sheet tab.
   * Shows a DR dialog then rolls the appropriate damage formula.
   * @param {PointerEvent} event
   * @param {HTMLElement} target
   */
  static async #onRollSpellDamage(event, target) {
    if (this.isEditMode) return
    const itemId = target.dataset.itemId
    const tier = target.dataset.damageTier
    const spell = this.actor.items.get(itemId)
    if (!spell) return

    const formulaMap = {
      standard: spell.system.damageDice,
      overpowered: spell.system.damageDiceOverpowered,
      overpowered2: spell.system.damageDiceOverpowered2,
    }
    const formula = formulaMap[tier]
    if (!formula) return

    const content = await foundry.applications.handlebars.renderTemplate("systems/fvtt-lethal-fantasy/templates/dialogs/spell-dr.hbs", {
      msg: game.i18n.localize("LETHALFANTASY.Combat.spellDRDialogMsg"),
      label: game.i18n.localize("LETHALFANTASY.Combat.spellDRLabel")
    })
    const manualDR = await foundry.applications.api.DialogV2.wait({
      window: { title: game.i18n.localize("LETHALFANTASY.Combat.spellDRDialogTitle") },
      classes: ["lethalfantasy"],
      position: { width: 320 },
      content,
      buttons: [
        {
          action: "noDR",
          type: "button",
          label: game.i18n.localize("LETHALFANTASY.Combat.spellNoDR"),
          icon: "fa-solid fa-wand-magic-sparkles",
          callback: () => 0
        },
        {
          action: "applyDR",
          type: "button",
          label: game.i18n.localize("LETHALFANTASY.Combat.spellApplyDR"),
          icon: "fa-solid fa-shield",
          callback: (event, button) => Number(button.form?.elements?.manualDr?.value) || 0
        },
        {
          action: "cancel",
          type: "button",
          label: game.i18n.localize("LETHALFANTASY.Combat.proceedNo"),
          callback: () => "cancel"
        }
      ],
      rejectClose: false
    })
    if (manualDR === null || manualDR === "cancel") return

    const rollOpts = {
      type: "spell-damage",
      rollType: "spell-damage",
      rollName: `${spell.name} — ${formula}`,
      isDamage: true,
      rollData: { isDamage: true },
      manualDR,
      actorId: this.actor.id,
      actorName: this.actor.name,
      actorImage: this.actor.img
    }
    await LethalFantasyRoll.rollSpellDamageToMessage(formula, rollOpts)
  }

  static #onCreateEquipment(event, target) {
  }

  _onRender(context, options) {
    const woundDescription = this.element.querySelectorAll('.wound-data')
    for (const input of woundDescription) {
      input.addEventListener("change", async (e) => {
        e.preventDefault();
        e.stopImmediatePropagation();
        const newValue = e.currentTarget.value
        const index = e.currentTarget.dataset.index
        const fieldName = e.currentTarget.dataset.name
        let tab = foundry.utils.duplicate(this.actor.system.hp.wounds)
        tab[index][fieldName] = newValue
        log(tab, index, fieldName, newValue)
        await this.actor.update({ "system.hp.wounds": tab });
      })
    }
    super._onRender(context, options);
  }


  /**
   * 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
    const el = event.currentTarget
    const rollType = el.dataset.rollType
    if (!rollType) return
    let rollKey = el.dataset.rollKey
    let rollDice = el.dataset.rollDice

    this.actor.prepareRoll(rollType, rollKey, rollDice)

  }
  // #endregion
}
