import { renderTemplate } from "../constants.js"
import { HtmlUtility } from "../html-utility.js";
import { RdDUtility } from "../rdd-utility.js";
import { ChatVente } from "./chat-vente.js";

export class DialogItemVente extends foundry.applications.api.DialogV2 {
  static async display({ item, quantiteMax = undefined }) {
    const quantite = quantiteMax ?? item.getQuantite() ?? 1
    const venteData = {
      item,
      alias: item.actor?.name ?? game.user.name,
      vendeurId: item.actor?.id,
      prixOrigine: item.calculerPrixCommercant(),
      prixUnitaire: item.calculerPrixCommercant(),
      prixLot: item.calculerPrixCommercant(),
      tailleLot: 1,
      nbLots: quantite,
      maxLots: quantite,
      quantiteMax: quantite,
      quantiteIllimite: item.isItemCommerce() ? quantiteMax == undefined : !item.parent,
      isOwned: item.parent,
    }
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-item-vente.hbs", venteData)
    const dialog = new DialogItemVente(venteData, content)
    dialog.render({ force: true })
    return dialog
  }

  constructor(venteData, content) {
    super({
      title: "Proposer",
      content,
      classes: ["dialogvente"],
      position: { width: 400, height: 'fit-content' },
      buttons: [
        { label: "Proposer", action: "proposer", callback: () => this.onProposer() }
      ]
    })
    this.venteData = venteData
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    el.querySelector(".tailleLot")?.addEventListener("change", event => this.setTailleLot(Number(event.currentTarget.value)))
    el.querySelector(".nbLots")?.addEventListener("change", event => this.setNbLots(Number(event.currentTarget.value)))
    el.querySelector(".quantiteIllimite")?.addEventListener("change", event => this.setQuantiteIllimite(event.currentTarget.checked))
    el.querySelector(".prixLot")?.addEventListener("change", event => this.setPrixLot(Number(event.currentTarget.value)))
    this.setQuantiteIllimite(this.venteData.quantiteIllimite)
  }

  async onProposer() {
    this.updateVente(this.getChoixVente())
    this.venteData["properties"] = this.venteData.item.getProprietes()
    if (this.venteData.isOwned) {
      if (this.venteData.nbLots * this.venteData.tailleLot > this.venteData.quantiteMax) {
        ui.notifications.warn(`Vous avez ${this.venteData.quantiteMax} ${this.venteData.item.name}, ce n'est pas suffisant pour vendre ${this.venteData.nbLots} de ${this.venteData.tailleLot}`)
        return
      }
    }
    await ChatVente.displayAchatVente(this.venteData)
  }

  updateVente(update) {
    foundry.utils.mergeObject(this.venteData, update)
  }

  getChoixVente() {
    const el = this.element
    return {
      nbLots: Number(el.querySelector(".nbLots")?.value ?? 0),
      tailleLot: Number(el.querySelector(".tailleLot")?.value ?? 0),
      quantiteIllimite: el.querySelector(".quantiteIllimite")?.checked ?? false,
      prixLot: Number(el.querySelector(".prixLot")?.value ?? 0)
    }
  }

  setPrixLot(prixLot) {
    this.venteData.prixLot = prixLot
  }

  setTailleLot(tailleLot) {
    const maxLots = Math.floor(this.venteData.quantiteMax / tailleLot)
    this.updateVente({
      tailleLot,
      nbLots: Math.min(maxLots, this.venteData.nbLots),
      maxLots,
      prixLot: (tailleLot * this.venteData.prixOrigine).toFixed(2)
    })
    const el = this.element
    const prix = el.querySelector(".prixLot")
    if (prix) prix.value = this.venteData.prixLot
    const nb = el.querySelector(".nbLots")
    if (nb) {
      nb.value = this.venteData.nbLots
      nb.setAttribute("max", this.venteData.maxLots)
    }
  }

  setNbLots(nbLots) {
    this.updateVente({
      nbLots: this.venteData.isOwned ? Math.max(0, Math.min(nbLots, this.venteData.maxLots)) : nbLots
    })
    const nb = this.element.querySelector(".nbLots")
    if (nb) nb.value = this.venteData.nbLots
  }

  setQuantiteIllimite(checked) {
    this.updateVente({ quantiteIllimite: checked })
    const el = this.element
    const label = el.querySelector(".label-quantiteIllimite")
    if (label) label.textContent = checked ? "Illimités" : "disponibles"
    const nb = el.querySelector(".nbLots")
    if (nb) HtmlUtility.showControlWhen(nb, !checked)
  }
}
