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

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

export class DialogGererDeniers extends HandlebarsApplicationMixin(ApplicationV2) {

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

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

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

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

  async _prepareContext() {
    const monnaies = this.actor.itemTypes[ITEM_TYPES.monnaie] || []
    const conteneurs = this.actor.itemTypes[ITEM_TYPES.conteneur] || []
    const fortune = Monnaie.toSolsDeniers(this.actor.getFortune())

    const monnaieData = monnaies.map(piece => ({
      id: piece.id,
      name: piece.name,
      img: piece.img,
      quantite: piece.system.quantite,
      cout: piece.system.cout,
      conteneurId: this.actor.findConteneur(piece)?.id || ""
    }))

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

    return { monnaies: monnaieData, conteneurs: conteneurOptions, fortune }
  }

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

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

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

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

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

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