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

const __ALLOWED_ITEM_CELLULE = { talent: 1, ressource: 1, contact: 1, equipement: 1, protection: 1, artefact: 1, arme: 1, monnaie: 1 }

export default class HawkmoonCelluleSheet extends HawkmoonActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    ...super.DEFAULT_OPTIONS,
    classes: [...super.DEFAULT_OPTIONS.classes],
    window: {
      ...super.DEFAULT_OPTIONS.window,
      title: "SHEETS.Actor.cellule",
    },
    actions: {
      ...super.DEFAULT_OPTIONS.actions,
      editActor: HawkmoonCelluleSheet.#onEditActor,
      deleteActor: HawkmoonCelluleSheet.#onDeleteActor,
    },
  }

  /** @override */
  static PARTS = {
    sheet: {
      template: "systems/fvtt-hawkmoon-cyd/templates/cellule-sheet.hbs",
    },
  }

  /** @override */
  tabGroups = { primary: "talents" }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    const actor = this.document

    // Add cellule-specific data
    context.talents = foundry.utils.duplicate(actor.getTalents() || {})
    context.ressources = foundry.utils.duplicate(actor.getRessources ? actor.getRessources() : [])
    context.contacts = foundry.utils.duplicate(actor.getContacts ? actor.getContacts() : [])
    context.members = this.#getMembers()
    context.equipements = foundry.utils.duplicate(actor.getEquipments ? actor.getEquipments() : [])
    context.artefacts = foundry.utils.duplicate(actor.getArtefacts ? actor.getArtefacts() : [])
    context.armes = foundry.utils.duplicate(actor.getWeapons ? actor.getWeapons() : [])
    context.monnaies = foundry.utils.duplicate(actor.getMonnaies ? actor.getMonnaies() : [])
    context.protections = foundry.utils.duplicate(actor.getArmors ? actor.getArmors() : [])
    context.richesse = actor.computeRichesse ? actor.computeRichesse() : 0
    context.valeurEquipement = actor.computeValeurEquipement ? actor.computeValeurEquipement() : 0
    context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(actor.system.description || "", { async: true })

    return context
  }

  /**
   * Get members of the cellule with full actor data
   * @returns {Array}
   * @private
   */
  #getMembers() {
    let membersFull = []
    for (let memberId of this.actor.system.members) {
      let actor = game.actors.get(memberId)
      if (actor) {
        membersFull.push({ name: actor.name, id: actor.id, img: actor.img })
      }
    }
    return membersFull
  }

  /**
   * Override _onDropItem to filter allowed item types for cellule
   * @override
   */
  async _onDropItem(event, data) {
    const item = await fromUuid(data.uuid)

    // Check if item type is allowed for cellule
    if (!__ALLOWED_ITEM_CELLULE[item.type]) {
      ui.notifications.warn(`Le type d'item ${item.type} n'est pas autorisé pour une cellule`)
      return false
    }

    return super._onDropItem(event, data)
  }

  /**
   * Override _onDropActor to handle adding members
   * @override
   */
  async _onDropActor(event, data) {
    const droppedActor = await fromUuid(data.uuid)

    if (droppedActor.type !== "personnage") {
      ui.notifications.warn("Seuls les personnages peuvent être ajoutés à une cellule")
      return false
    }

    // Check if already a member
    const isMember = this.actor.system.members.includes(droppedActor.id)
    if (isMember) {
      ui.notifications.warn("Ce personnage est déjà membre de cette cellule")
      return false
    }

    // Add member ID
    const members = [...this.actor.system.members, droppedActor.id]
    await this.actor.update({ "system.members": members })
    return true
  }

  // #region Cellule-specific Actions

  /**
   * Edit an actor (member)
   * @param {Event} event
   * @param {HTMLElement} target
   * @private
   */
  static async #onEditActor(event, target) {
    const li = target.closest(".item")
    const actorId = li?.dataset.actorId
    if (!actorId) return
    const actor = game.actors.get(actorId)
    if (actor) actor.sheet.render(true)
  }

  /**
   * Delete an actor (remove member)
   * @param {Event} event
   * @param {HTMLElement} target
   * @private
   */
  static async #onDeleteActor(event, target) {
    const li = target.closest(".item")
    const actorId = li?.dataset.actorId
    if (actorId) {
      const members = this.actor.system.members.filter(id => id !== actorId)
      await this.actor.update({ "system.members": members })
    }
  }

  // #endregion
}
