import { ITEM_TYPES } from "./constants.js"
import { Grammar } from "./grammar.js"
import { Misc } from "./misc.js"

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

const INVENTORY_TYPES = new Set([
  ITEM_TYPES.herbe, ITEM_TYPES.plante, ITEM_TYPES.ingredient,
  ITEM_TYPES.objet, ITEM_TYPES.nourritureboisson, ITEM_TYPES.faune,
  ITEM_TYPES.potion,
])

export class DialogVerifierIngredients extends HandlebarsApplicationMixin(ApplicationV2) {

  static DEFAULT_OPTIONS = {
    tag: "form",
    classes: ["dialog-verifier-ingredients"],
    form: {
      submitOnChange: false,
      closeOnSubmit: false
    },
    position: {
      width: 600,
      height: "auto"
    },
    window: {
      title: "Vérifier les ingrédients",
      icon: "fa-solid fa-flask"
    }
  }

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

  static async create(item, actor) {
    const dialog = new DialogVerifierIngredients({ item, actor })
    dialog.render(true)
  }

  constructor(options) {
    super(options)
    this.item = options.item
    this.actor = options.actor
  }

  async _prepareContext() {
    const ingredients = Misc.safeJsonParse(this.item.system.ingredients, [])
    const inventoryItems = this.actor.items.filter(i => INVENTORY_TYPES.has(i.type))

    const rows = ingredients.map(ing => {
      const matches = inventoryItems.filter(inv => Grammar.matchName(ing.nom, inv.name))
      const foundQty = matches.reduce((sum, inv) => sum + (parseInt(inv.system.quantite) || 0), 0)
      const requiredQty = parseInt(ing.quantite) || 1
      return {
        nom: ing.nom,
        type: ing.type,
        quantiteRequise: requiredQty,
        quantiteTrouvee: foundQty,
        unite: ing.unite,
        suffisant: foundQty >= requiredQty,
        present: foundQty > 0,
        items: matches.map(inv => ({ name: inv.name, qty: parseInt(inv.system.quantite) || 0 })),
      }
    })

    const allOk = rows.every(r => r.suffisant)

    return {
      ingredients: rows,
      recette: this.item.name,
      personnage: this.actor.name,
      allOk,
    }
  }

  async _onRender(context, options) {
    this.element.querySelectorAll('.ingredient-item-edit').forEach(el => {
      el.addEventListener('click', async event => {
        const item = this.actor.items.get(event.currentTarget.dataset.itemId)
        if (item) item.sheet.render(true)
      })
    })
  }
}
