import { ITEM_TYPES, renderTemplate } from "../constants.js"
import { RdDItemCompetence } from "../item-competence.js"
import { ChatUtility } from "../chat-utility.js"
import { Misc } from "../misc.js"

const CODES_COMPETENCES_VOYAGE = ["Extérieur", "Forêt", "Montagne", "Marais", "Glace", "Equitation"]
const TABLEAU_FATIGUE_MARCHE = [
  { code: "aise", label: "Aisé", description: "Route ou chemin",
    survies: ["Extérieur", "Equitation"],
    vitesses: [{ vitesse: 4, fatigue: 1 }, { vitesse: 6, fatigue: 2 }, { vitesse: 8, fatigue: 3 }, { vitesse: 10, fatigue: 4 }, { vitesse: 12, fatigue: 6 }] },
  { code: "malaise", label: "Malaisé", description: "Hors piste (herbes et buissons)",
    survies: ["Extérieur", "Equitation"],
    vitesses: [{ vitesse: 4, fatigue: 2 }, { vitesse: 6, fatigue: 3 }, { vitesse: 8, fatigue: 4 }, { vitesse: 10, fatigue: 6 }] },
  { code: "difficile", label: "Difficile", description: "Hors piste (collines, forêt)",
    survies: ["Extérieur", "Forêt", "Glace", "Equitation"],
    vitesses: [{ vitesse: 4, fatigue: 3 }, { vitesse: 6, fatigue: 4 }, { vitesse: 8, fatigue: 6 }] },
  { code: "tresdifficile", label: "Très difficile", description: "Hors piste (montagne, jungle, marais)",
    survies: ["Forêt", "Montagne", "Marais", "Glace"],
    vitesses: [{ vitesse: 4, fatigue: 4 }, { vitesse: 6, fatigue: 6 }] },
]

export class DialogFatigueVoyage extends foundry.applications.api.DialogV2 {
  static dialog = undefined

  static async create() {
    if (!game.user.isGM) return
    if (!DialogFatigueVoyage.dialog) {
      const parameters = {
        tableauFatigueMarche: TABLEAU_FATIGUE_MARCHE,
        playerActors: game.actors.filter(actor => actor.isPersonnageJoueur())
          .map(actor => DialogFatigueVoyage.prepareActorParameters(actor)),
        nombreHeures: 1,
      }
      DialogFatigueVoyage.setModeDeplacement(parameters, undefined, undefined)
      const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/voyage/dialog-fatigue-voyage.hbs", parameters)
      DialogFatigueVoyage.dialog = new DialogFatigueVoyage(content, parameters)
    }
    DialogFatigueVoyage.dialog.render({ force: true })
  }

  static setModeDeplacement(parameters, code, vitesse) {
    const ligne = TABLEAU_FATIGUE_MARCHE.find(it => it.code == code) ?? TABLEAU_FATIGUE_MARCHE[0]
    const rythme = ligne.vitesses.find(it => it.vitesse == vitesse) ?? ligne.vitesses[0]
    parameters.typeTerrain = ligne
    parameters.vitesseDeplacement = rythme.vitesse
    parameters.fatigueHoraire = rythme.fatigue
    parameters.playerActors.forEach(voyageur =>
      DialogFatigueVoyage.selectSurvie(voyageur, parameters.typeTerrain.code)
    )
  }

  static prepareActorParameters(actor) {
    const actorParameters = { id: actor.id, actor, selected: true, ajustementFatigue: 0, survies: {} }
    const competencesVoyage = {}
    CODES_COMPETENCES_VOYAGE.forEach(codeSurvie => {
      competencesVoyage[codeSurvie] = RdDItemCompetence.findCompetence(actor.itemTypes[ITEM_TYPES.competence], codeSurvie, { onMessage: () => {} })
    })
    TABLEAU_FATIGUE_MARCHE.forEach(terrain => {
      actorParameters.survies[terrain.code] = Misc.join(
        terrain.survies.map(survie => {
          const niveau = competencesVoyage[survie]?.system.niveau
          return `${survie}: ${niveau}`
        }), ", ")
    })
    return actorParameters
  }

  static selectSurvie(actorParameters, code) {
    actorParameters.survieCourante = actorParameters.survies[code]
  }

  constructor(content, parameters) {
    super({
      title: "Fatigue de voyage",
      content,
      classes: ["dialog-fatigue-voyage"],
      position: { width: 600 },
      buttons: [{ label: "Fermer", action: "close" }]
    })
    this.parameters = parameters
    this.controls = {}
  }

  _onRender(context) {
    if (!this._rendered) {
      this.element.querySelector('select[name="code-terrain"]')?.focus()
    }
    this._rendered = true
    super._onRender(context)
    const el = this.element
    el.querySelector('select[name="code-terrain"]')?.addEventListener("change", () => this.changeParameters())
    el.querySelector('select[name="vitesse-deplacement"]')?.addEventListener("change", () => this.changeParameters())
    el.querySelector('input[name="nombre-heures"]')?.addEventListener("change", () => this.changeParameters())
    el.querySelectorAll('.list-item input[name="ajustement-fatigue"]').forEach(i =>
      i.addEventListener("change", () => this.changeParameters())
    )
    el.querySelector('button[name="appliquer-fatigue"]')?.addEventListener("click", () => this.appliquerFatigue())
  }

  _val(sel) { return this.element.querySelector(sel)?.value ?? "" }

  changeParameters() {
    this.changeTerrain(this._val('select[name="code-terrain"]'))
    this.changeVitesse(this._val('select[name="vitesse-deplacement"]'))
    this.changeNombreHeures(this._val('input[name="nombre-heures"]'))
    this.setFatigue()
  }

  async changeTerrain(codeTerrain) {
    if (this.parameters.typeTerrain.code != codeTerrain) {
      const vitesseSelect = this.element.querySelector('select[name="vitesse-deplacement"]')
      const vitesse = vitesseSelect?.value
      if (vitesseSelect) vitesseSelect.innerHTML = ""
      DialogFatigueVoyage.setModeDeplacement(this.parameters, codeTerrain, vitesse)
      for (const rythme of this.parameters.typeTerrain.vitesses) {
        const optHtml = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/voyage/option-vitesse-fatigue.hbs", rythme)
        if (vitesseSelect) vitesseSelect.insertAdjacentHTML("beforeend", optHtml)
      }
      if (vitesseSelect) vitesseSelect.value = this.parameters.vitesseDeplacement
      vitesseSelect?.dispatchEvent(new Event("change"))
      this.getActorRows().forEach(row => {
        const label = row.querySelector("label.voyage-liste-survies")
        if (label) label.textContent = this.$extractActorParameters(row).survieCourante
      })
    }
  }

  async changeVitesse(vitesse) {
    if (this.parameters.vitesseDeplacement != vitesse) {
      DialogFatigueVoyage.setModeDeplacement(this.parameters, this.parameters.typeTerrain.code, vitesse)
    }
  }

  async changeNombreHeures(nombreHeures) {
    this.parameters.nombreHeures = parseInt(nombreHeures)
  }

  async setFatigue() {
    const baseFatigue = this.parameters.nombreHeures * this.parameters.fatigueHoraire
    const bf = this.element.querySelector('input[name="base-fatigue"]')
    if (bf) bf.value = baseFatigue
    this.updateActorTotalFatigue(baseFatigue)
  }

  async updateActorTotalFatigue(baseFatigue) {
    this.getActorRows().forEach(row => {
      const actor = this.$extractActorParameters(row)
      const tf = row.querySelector('input[name="total-fatigue"]')
      if (tf) tf.value = actor.ajustement + baseFatigue
    })
  }

  async appliquerFatigue() {
    const fatigueBase = parseInt(this._val('input[name="base-fatigue"]') ?? 0)
    this.getActorRows()
      .map(row => this.$extractActorParameters(row))
      .filter(it => it.selected)
      .forEach(async it => {
        const perteFatigue = fatigueBase + it.ajustement
        await ChatMessage.create({
          whisper: ChatUtility.getOwners(it.actor),
          content: await renderTemplate(
            "systems/foundryvtt-reve-de-dragon/templates/voyage/chat-fatigue_voyage.hbs",
            foundry.utils.mergeObject(it, {
              parameters: this.parameters,
              fatigueBase,
              perteFatigue,
              isVoyage: fatigueBase == this.parameters.nombreHeures * this.parameters.fatigueHoraire
            }, { inplace: false })
          )
        })
        await it.actor.santeIncDec("fatigue", perteFatigue)
      })
  }

  getActorRows() {
    return Array.from(this.element.querySelectorAll("div.fatigue-actors-list li.list-item"))
  }

  $extractActorParameters(actorRow) {
    const actorId = actorRow.dataset.actorId
    const actorParameters = this.parameters.playerActors.find(it => it.id == actorId)
    const actor = game.actors.get(actorId)
    if (!actor) {
      ui.notifications.warn(`Acteur ${actorId} introuvable`)
      return { ajustement: 0, selected: false, survieCourante: "" }
    }
    actorParameters.ajustement = parseInt(actorRow.querySelector('input[name="ajustement-fatigue"]')?.value ?? 0)
    actorParameters.selected = !!actorRow.querySelector('input[name="selectionner-acteur"]')?.checked
    return actorParameters
  }

  async close() {
    DialogFatigueVoyage.dialog = undefined
    await super.close()
  }
}
