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

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

export class DialogGererHerbes extends HandlebarsApplicationMixin(ApplicationV2) {

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

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


  }

  static async create(actor) {
    const dialog = new DialogGererHerbes({ 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 herbes = this.actor.itemTypes[ITEM_TYPES.herbe] || []
    const conteneurs = this.actor.itemTypes[ITEM_TYPES.conteneur] || []

    const herbeData = herbes.map(herbe => ({
      id: herbe.id,
      name: herbe.name,
      img: herbe.img,
      quantite: herbe.system.quantite,
      categorie: herbe.system.categorie,
      niveau: herbe.system.niveau,
      isHerbeAPotion: herbe.isHerbeAPotion(),
      conteneurId: this.actor.findConteneur(herbe)?.id || ""
    }))

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

    return { herbes: herbeData, conteneurs: conteneurOptions }
  }

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

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

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

    this.element.querySelectorAll(".herbe-decoction").forEach(el => {
      el.addEventListener("click", async event => {
        const herbeId = RdDSheetUtility.getItemId(event)
        const herbe = this.actor.items.get(herbeId)
        if (herbe) this.actor.fabriquerDecoctionHerbe(herbe)
      })
    })

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

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

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

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

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