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

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

export class DialogGererIngredients extends HandlebarsApplicationMixin(ApplicationV2) {

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

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

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

    const ingredientData = ingredients.map(ing => ({
      id: ing.id,
      name: ing.name,
      img: ing.img,
      quantite: ing.system.quantite,
      categorie: ing.system.categorie,
      conteneurId: this.actor.findConteneur(ing)?.id || ""
    }))

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

    return { ingredients: ingredientData, conteneurs: conteneurOptions }
  }

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

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

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

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

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

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

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

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