import { ITEM_TYPES } from "./constants.js"
import { RdDSheetUtility } from "./rdd-sheet-utility.js"

const { HandlebarsApplicationMixin, ApplicationV2 } = foundry.applications.api

export class DialogGererPotions extends HandlebarsApplicationMixin(ApplicationV2) {

  static DEFAULT_OPTIONS = {
    tag: "form",
    classes: ["dialog-gerer-potions"],
    form: {
      submitOnChange: false,
      closeOnSubmit: false
    },
    position: {
      width: 700,
      height: "auto"
    },
    window: {
      title: "Gérer ses potions",
      icon: "fa-solid fa-flask"
    }
  }

  static PARTS = {
    form: { template: "systems/foundryvtt-reve-de-dragon/templates/actor/dialog-gerer-potions.hbs" }
  }

  static async create(actor) {
    const dialog = new DialogGererPotions({ actor })
    dialog.render(true)
  }

  constructor(options) {
    super(options)
    this.actor = options.actor
    this._onItemChange = (item) => {
      if (item.parent === this.actor) this.render()
    }
    Hooks.on("updateItem", this._onItemChange)
    Hooks.on("createItem", this._onItemChange)
    Hooks.on("deleteItem", this._onItemChange)
  }

  _onClose() {
    super._onClose()
    Hooks.off("updateItem", this._onItemChange)
    Hooks.off("createItem", this._onItemChange)
    Hooks.off("deleteItem", this._onItemChange)
  }

  async _prepareContext() {
    const potions = this.actor.itemTypes[ITEM_TYPES.potion] || []
    const conteneurs = this.actor.itemTypes[ITEM_TYPES.conteneur] || []

    const potionData = potions.map(p => ({
      id: p.id,
      name: p.name,
      img: p.img,
      quantite: p.system.quantite,
      categorie: p.system.categorie,
      conteneurId: this.actor.findConteneur(p)?.id || "",
      magique: p.system.magique,
    }))

    const conteneurOptions = [
      { id: "", name: "— Aucun —" },
      ...conteneurs.map(c => ({ id: c.id, name: c.name }))
    ]

    return { potions: potionData, conteneurs: conteneurOptions }
  }

  async _onRender(context, options) {
    this.element.querySelectorAll(".potion-moins").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (!potion) return
        const q = Number(potion.system.quantite)
        if (q <= 0) return
        await potion.update({ "system.quantite": Math.max(0, q - 1) })
        this.render(true)
      })
    })

    this.element.querySelectorAll(".potion-plus").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (!potion) return
        await potion.update({ "system.quantite": Number(potion.system.quantite) + 1 })
        this.render(true)
      })
    })

    this.element.querySelectorAll(".potion-consommer").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (potion) {
          await this.actor.consommerPotion(potion)
          this.render(true)
        }
      })
    })

    this.element.querySelectorAll(".potion-vendre").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (potion) await potion.proposerVente()
      })
    })

    this.element.querySelectorAll(".potion-chat").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (potion) potion.postItemToChatCompact()
      })
    })

    this.element.querySelectorAll(".potion-edit").forEach(el => {
      el.addEventListener("click", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const potion = this.actor.items.get(id)
        if (potion) potion.sheet.render(true)
      })
    })

    this.element.querySelectorAll(".potion-conteneur").forEach(el => {
      el.addEventListener("change", async event => {
        const id = RdDSheetUtility.getItemId(event)
        const newConteneurId = String(event.currentTarget.value)
        const potion = this.actor.items.get(id)
        if (!potion) return

        const currentConteneur = this.actor.findConteneur(potion)
        const newConteneur = newConteneurId ? this.actor.items.get(newConteneurId) : null

        if (currentConteneur) {
          await this.actor.enleverDeConteneur(potion, currentConteneur, () => {})
        }
        if (newConteneur) {
          await this.actor.ajouterDansConteneur(potion, newConteneur, () => {})
        }
      })
    })
  }
}
