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

export default class HellbornCharacterSheet extends HellbornActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["character"],
    position: {
      width: 860,
      height: 620,
    },
    window: {
      contentClasses: ["character-content"],
    },
    actions: {
      createEquipment: HellbornCharacterSheet.#onCreateEquipment,
      createArmor: HellbornCharacterSheet.#onCreateArmor,
      createWeapon: HellbornCharacterSheet.#onCreateWeapon,
      createDeal: HellbornCharacterSheet.#onCreateDeal,
      createMalefica: HellbornCharacterSheet.#onCreateMalefica,
      createRitual: HellbornCharacterSheet.#onCreateRitual,
      createPerk: HellbornCharacterSheet.#onCreatePerk,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-hellborn/templates/character-main.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    status: {
      template: "systems/fvtt-hellborn/templates/character-status.hbs",
    },
    maleficas: {
      template: "systems/fvtt-hellborn/templates/character-maleficas.hbs",
    },
    equipment: {
      template: "systems/fvtt-hellborn/templates/character-equipment.hbs",
    },
    biography: {
      template: "systems/fvtt-hellborn/templates/character-biography.hbs",
    },
  }

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

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    const tabs = {
      status: { id: "status", group: "sheet", icon: "fa-solid fa-compass", label: "HELLBORN.Label.status" },
      maleficas: { id: "maleficas", group: "sheet", icon: "fa-solid fa-compass", label: "HELLBORN.Label.maleficas" },
      equipment: { id: "equipment", group: "sheet", icon: "fa-solid fa-shapes", label: "HELLBORN.Label.equipment" },
      biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "HELLBORN.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()

    const doc = this.document
    context.trait = doc.itemTypes['species-trait']?.[0]
    context.upright = doc.itemTypes.tarot.find(t => t.system.orientation === "Upright")
    context.downright = doc.itemTypes.tarot.find(t => t.system.orientation === "Downright")

    return context
  }

  /** @override */
  async _preparePartContext(partId, context) {
    const doc = this.document
    context.systemFields = this.document.system.schema.fields
    switch (partId) {
      case "main":
        break
      case "status":
        context.tab = context.tabs.status
        context.perks = doc.itemTypes.perk
        // Sort the perks by system.role and then by the system.level
        context.perks.sort((a, b) => {
          if (a.system.role === b.system.role) {
            return a.system.level.localeCompare(b.system.level)
          }
          return a.system.role.localeCompare(b.system.role)
        })
        break;
      case "maleficas":
        context.tab = context.tabs.maleficas
        context.maleficas = doc.itemTypes.malefica
        // Sort the maleficas by system.domain and then by the system.level
        context.maleficas.sort((a, b) => {
          if (a.system.domain === b.system.domain) {
            return a.system.level.localeCompare(b.system.level)
          }
          return a.system.domain.localeCompare(b.system.domain)
        })
        context.rituals = doc.itemTypes.ritual
        context.rituals.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "equipment":
        context.tab = context.tabs.equipment
        context.weapons = doc.itemTypes.weapon
        context.weapons.sort((a, b) => a.name.localeCompare(b.name))
        context.armors = doc.itemTypes.armor
        context.armors.sort((a, b) => a.name.localeCompare(b.name))
        context.equipments = doc.itemTypes.equipment
        context.equipments.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "biography":
        context.tab = context.tabs.biography
        context.deals = doc.itemTypes.deal
        context.enrichedBackstory = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.backstory, { async: true })
        context.enrichedAppearance = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.appearance, { async: true })
        context.enrichedScars = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.scars, { async: true })
        context.enrichedLikes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.likes, { async: true })
        context.enrichedDislikes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.dislikes, { async: true })
        context.enrichedFears = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.fears, { async: true })
        context.enrichedVices = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.vices, { async: true })
        context.enrichedGoals = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.goals, { async: true })
        context.enrichedAmbitions = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.ambitions, { async: true })
        context.enrichedValues = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.values, { async: true })
        context.enrichedBonds = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.bonds, { async: true })
        context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.notes, { async: true })
        break
    }
    return context
  }


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

  static #onCreateDeal(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HELLBORN.Label.newDeal"), type: "deal" }])
  }

  static #onCreateMalefica(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HELLBORN.Label.newMalefica"), type: "malefica" }])
  }

  static #onCreateRitual(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HELLBORN.Label.newRitual"), type: "ritual" }])
  }

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

  static #onCreateArmor(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HELLBORN.Label.newArmor"), type: "armor" }])
  }

  static #onCreatePerk(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("HELLBORN.Label.newPerk"), type: "perk" }])
  }


  /**
   * 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
    let li
    let statKey
    switch (rollType) {
      case "stat":
        statKey = $(event.currentTarget).data("stat-id");
        item = this.actor.system.stats[statKey];
        break
      case "weapon":
      case "damage":
        li = $(event.currentTarget).parents(".item");
        item = this.actor.items.get(li.data("item-id"));
        break
      default:
        throw new Error(`Unknown roll type ${rollType}`)
    }
    await this.document.system.roll(rollType, item)
  }

  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)
      if (item.type === "tarot") {
        // Delete the existing tarot item
        const existingTarot = this.document.items.find(i => i.type === "tarot" && i.system.orientation === item.system.orientation)
        if (existingTarot) {
          await existingTarot.delete()
          // Display info message
          ui.notifications.info(game.i18n.localize("HELLBORN.Notifications.tarotDeleted") + existingTarot.name)
        }
      }
      if (item.type === "species-trait") {
        // Check if the item is already in the actor
        const existingTrait = this.document.items.find(i => i.type === "species-trait" && i.name === item.name)
        if (existingTrait) {
          await existingTrait.delete()
          // Display info message
          ui.notifications.info(game.i18n.localize("HELLBORN.Notifications.speciesTraitDeleted")+ existingTrait.name)
        }
      }
      return super._onDropItem(item)
    }

  }

}
