import { RdDBaseActorSheetV2 } from "./base-actor-sheet.mjs"
import { RdDUtility } from "../../rdd-utility.js"
import { HtmlUtility } from "../../html-utility.js"
import { RdDBonus } from "../../rdd-bonus.js"
import { Misc } from "../../misc.js"
import { RdDCombat } from "../../combat/rdd-combat.js"
import { CARACS, RdDCarac } from "../../rdd-carac.js"
import { DialogSplitItem } from "../../dialog-split-item.js"
import { ReglesOptionnelles } from "../../settings/regles-optionnelles.js"
import { RdDSheetUtility } from "../../rdd-sheet-utility.js"
import { MAINS_DIRECTRICES } from "../../actor.js"
import { ACTOR_TYPES, ITEM_TYPES } from "../../constants.js"
import { RdDItem } from "../../item.js"
import { RdDItemCompetence } from "../../item-competence.js"
import { RdDItemBlessure } from "../../item/blessure.js"
import { RdDEmpoignade } from "../../combat/rdd-empoignade.js"
import { RdDCoeur } from "../../coeur/rdd-coeur.js"
import { AppPersonnageAleatoire } from "../../actor/random/app-personnage-aleatoire.js"
import { RdDTextEditor } from "../../apps/rdd-text-roll-editor.js"
import { MORAL } from "../../moral/apprecier.mjs"
import { RdDItemSort } from "../../item-sort.js"

export class RdDActorSheetV2 extends RdDBaseActorSheetV2 {

  static TYPE = ACTOR_TYPES.personnage

  static DEFAULT_OPTIONS = Object.assign({}, RdDBaseActorSheetV2.DEFAULT_OPTIONS, {
    position: { width: 640 },
  })

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

  showCompNiveauBase = false
  vueArchetype = false
  armesList = []

  async _prepareContext() {
    const ctx = await super._prepareContext()
    ctx.options.showCompNiveauBase = this.showCompNiveauBase
    ctx.options.vueArchetype = this.vueArchetype
    ctx.biographie = await RdDTextEditor.enrichHTML(ctx.system.biographie, this.actor)
    ctx.notes = await RdDTextEditor.enrichHTML(ctx.system.notes, this.actor)

    foundry.utils.mergeObject(ctx.calc, {
      surenc: this.actor.computeMalusSurEncombrement(),
      surprise: RdDBonus.find(this.actor.getSurprise(false)).label,
      blessures: this.actor.computeResumeBlessure(ctx.system.blessures),
      caracTotal: RdDCarac.computeTotal(ctx.system.carac, ctx.system.beaute),
      caracTotalXp: RdDCarac.computeTotalXp(ctx.system.carac, ctx.system.beaute),
      surEncombrementMessage: this.actor.isSurenc() ? "Sur-Encombrement!" : "",
      malusArmure: this.actor.getMalusArmure(),
    })

    this._timerRecherche = undefined

    if (ctx.type == ACTOR_TYPES.personnage) {
      ctx.options.mainsDirectrices = MAINS_DIRECTRICES
      ctx.byCateg = Misc.classify(ctx.competences, it => it.system.categorie)
      foundry.utils.mergeObject(ctx.calc, {
        comptageArchetype: RdDItemCompetence.computeResumeArchetype(ctx.competences),
        competenceXPTotal: RdDItemCompetence.computeTotalXP(ctx.competences),
        sortsXPTotal: RdDItemSort.computeTotalXP(this.actor.itemTypes[ITEM_TYPES.sort]),
        fatigue: RdDUtility.calculFatigueHtml(ctx.system.sante.fatigue.value, ctx.system.sante.endurance.max),
      })
      this._amendTacheCommunes(ctx)

      ctx.competences.forEach(item => {
        item.system.isHidden = this.recherche
          ? !item.isNomLike(this.recherche.text)
          : (this.showCompNiveauBase && RdDItemCompetence.isNiveauBase(item))
        RdDItemCompetence.levelUp(item, ctx.system.compteurs.experience.value)
      })

      Object.values(ctx.system.carac).forEach(c => RdDCarac.levelUp(c))

      ctx.esquives = this.actor.getCompetencesEsquive()
      ctx.combat = this.actor.listActionsAttaque()
      ctx.empoignades = this.actor.getEmpoignades()
      this.armesList = ctx.combat

      ctx.ajustementsConditions = CONFIG.RDD.ajustementsConditions
      ctx.difficultesLibres = CONFIG.RDD.difficultesLibres

      ctx.hautreve = {
        isDemiReve: this.actor.isDemiReve(),
        cacheTMR: this.actor.isTMRCache(),
      }

      ctx.livresLus = ctx.livres.filter(l => l.system.estCopieLue)
      ctx.livres = ctx.livres.filter(l => !l.system.estCopieLue)

      ctx.race = this.actor.itemTypes[ITEM_TYPES.race].find(it => true)
      ctx.subacteurs = {
        vehicules: this.actor.listeVehicules(),
        montures: this.actor.listeMontures(),
        suivants: this.actor.listeSuivants(),
      }

      if (this.actor.getDraconics().find(it => it.system.niveau > -11) && !this.actor.isHautRevant()) {
        ui.notifications.error(`${this.actor.name} a des compétences draconiques, mais pas le don de Haut-Rêve!
          <br>Ajoutez-lui la tête "Don de Haut-Rêve" pour lui permettre d'utiliser ses compétences et d'accéder aux terres médianes du rêve`)
      }
    }
    else {
      console.error("Ouverture actor-sheet avec un acteur non personnage")
    }

    return ctx
  }

  _amendTacheCommunes(ctx) {
    ctx.taches.forEach(tache => {
      if (tache.isTacheCommune()) {
        const tacheCommune = tache.getTacheOuCommune()
        tache.system = foundry.utils.deepClone(tacheCommune.system)
        tache.system.tacheCommuneId = tache.system.tacheCommuneId
      }
      return tache
    })
  }

  async _onRender(context, options) {
    await super._onRender(context, options)
    if (!this.isEditable) return

    HtmlUtility.showControlWhen(this.html.find(".appliquerFatigue"), ReglesOptionnelles.isUsing("appliquer-fatigue"))

    this.html.find(".subacteur-open").click(async event => {
      const subActorId = RdDSheetUtility.getEventItemData(event, "subactor-id")
      this._openSubActeur(subActorId)
    })

    this.html.find(".show-hide-competences").click(async event => {
      this.showCompNiveauBase = !this.showCompNiveauBase
      this.render({ force: true })
    })

    this.html.find(".button-tmr-visu").click(async event => await this.actor.displayTMR("visu"))

    this.html.find(".sheet-possession-attack").click(async event => {
      const poss = RdDSheetUtility.getItem(event, this.actor)
      await this.actor.conjurerPossession(poss)
    })

    this.html.find(".subacteur-coeur-toggle a").click(async event => {
      const subActorId = RdDSheetUtility.getEventItemData(event, "subactor-id")
      const coeurNombre = $(event.currentTarget).data("numero-coeur")
      await RdDCoeur.toggleSubActeurCoeur(this.actor.id, subActorId, coeurNombre)
    })
    this.html.find(".subacteur-tendre-moment").click(async event => {
      const subActorId = RdDSheetUtility.getEventItemData(event, "subactor-id")
      await RdDCoeur.startSubActeurTendreMoment(this.actor.id, subActorId)
    })
    this.html.find(".subacteur-delete").click(async event => {
      const li = RdDSheetUtility.getEventElement(event)
      const subActorId = li.data("subactor-id")
      this._deleteSubActeur(subActorId, li)
    })

    this.html.find("input.derivee-value[name='system.compteurs.stress.value']").change(async event =>
      await this.actor.updateCompteurValue("stress", parseInt(event.target.value))
    )
    this.html.find("input.derivee-value[name='system.compteurs.experience.value']").change(async event =>
      await this.actor.updateCompteurValue("experience", parseInt(event.target.value))
    )

    this.html.find(".creer-tache").click(async event => await this._createEmptyTache())
    this.html.find(".creer-une-oeuvre").click(async event => await this._selectTypeOeuvreToCreate())
    this.html.find(".creer-tache-blessure-legere").click(async event => await RdDItemBlessure.createTacheSoinBlessure(this.actor, 2))
    this.html.find(".creer-tache-blessure-grave").click(async event => await RdDItemBlessure.createTacheSoinBlessure(this.actor, 4))
    this.html.find(".creer-tache-blessure-critique").click(async event => await RdDItemBlessure.createTacheSoinBlessure(this.actor, 6))

    this.html.find(".blessure-premierssoins-done").change(async event => {
      await this._getBlessure(event)?.setSoinsBlessure({ premierssoins: { done: event.currentTarget.checked } })
    })
    this.html.find(".blessure-soinscomplets-done").change(async event => {
      await this._getBlessure(event)?.setSoinsBlessure({ soinscomplets: { done: event.currentTarget.checked } })
    })
    this.html.find(".blessure-premierssoins-bonus").change(async event => {
      await this._getBlessure(event)?.setSoinsBlessure({ premierssoins: { bonus: Number(event.currentTarget.value) } })
    })
    this.html.find(".blessure-soinscomplets-bonus").change(async event => {
      await this._getBlessure(event)?.setSoinsBlessure({ soinscomplets: { bonus: Number(event.currentTarget.value) } })
    })

    this.html.find(".roll-chance-actuelle").click(async event => await this.actor.rollCarac(CARACS.CHANCE_ACTUELLE))
    this.html.find(".button-appel-chance").click(async event => await this.actor.rollAppelChance())

    this.html.find('[name="jet-astrologie"]').click(async event => await this.actor.astrologieNombresAstraux())
    this.html.find(".action-tache").click(async event => await this.actor.rollTache(RdDSheetUtility.getItemId(event)))
    this.html.find(".meditation-label a").click(async event => await this.actor.rollMeditation(RdDSheetUtility.getItemId(event)))

    this.html.find(".action-chant").click(async event => await this.actor.rollChant(RdDSheetUtility.getItemId(event)))
    this.html.find(".action-danse").click(async event => await this.actor.rollDanse(RdDSheetUtility.getItemId(event)))
    this.html.find(".action-musique").click(async event => await this.actor.rollMusique(RdDSheetUtility.getItemId(event)))
    this.html.find(".action-oeuvre").click(async event => await this.actor.rollOeuvre(RdDSheetUtility.getItemId(event)))
    this.html.find(".action-jeu").click(async event => await this.actor.rollJeu(RdDSheetUtility.getItemId(event)))
    this.html.find(".action-recettecuisine").click(async event => await this.actor.rollRecetteCuisine(RdDSheetUtility.getItemId(event)))

    this.html.find(".description-aleatoire").click(async event => new AppPersonnageAleatoire(this.actor).render({ force: true }))

    this.html.find(".gerer-herbes").click(async event => {
      const { DialogGererHerbes } = await import("../../dialog-gerer-herbes.js")
      DialogGererHerbes.create(this.actor)
    })
    this.html.find(".gerer-ingredients").click(async event => {
      const { DialogGererIngredients } = await import("../../dialog-gerer-ingredients.js")
      DialogGererIngredients.create(this.actor)
    })
    this.html.find(".gerer-deniers").click(async event => {
      const { DialogGererDeniers } = await import("../../dialog-gerer-deniers.js")
      DialogGererDeniers.create(this.actor)
    })
    this.html.find(".gerer-potions").click(async event => {
      const { DialogGererPotions } = await import("../../dialog-gerer-potions.js")
      DialogGererPotions.create(this.actor)
    })

    if (game.user.isGM) {
      this.html.find(".experiencelog-delete").click(async event => {
        const li = this.html.find(event.currentTarget)?.parents(".experiencelog")
        const key = Number(li.data("key") ?? -1)
        await this.actor.deleteExperienceLog(key, 1)
      })
      this.html.find(".experiencelog-delete-previous").click(async event => {
        const li = this.html.find(event.currentTarget)?.parents(".experiencelog")
        const key = Number(li.data("key") ?? -1)
        await this.actor.deleteExperienceLog(0, key + 1)
      })
      this.html.find(".forcer-tmr-aleatoire").click(async event => await this.actor.reinsertionAleatoire("Action MJ"))
      this.html.find(".don-de-haut-reve").click(async event => await this.actor.addDonDeHautReve())
      this.html.find(".afficher-tmr").click(async event => await this.actor.changeTMRVisible())
    }

    this.html.find(".roll-reve-actuel").click(async event => await this.actor.rollReveActuel({ resistance: false }))
    this.html.find(".button-reve-resistance").click(async event => await this.actor.rollReveResistance())
    this.html.find(".action-empoignade").click(async event => await RdDEmpoignade.onAttaqueEmpoignadeFromItem(RdDSheetUtility.getItem(event, this.actor)))

    this.html.find(".roll-arme").click(async event => {
      const action = this._getActionCombat(event)
      await this.actor.rollArme(action.arme, action.main)
    })

    this.html.find(".roll-init-arme").click(async event => {
      const combatant = game.combat.combatants.find(c => c.actor.id == this.actor.id)
      if (combatant) {
        RdDCombat.rollInitiativeAction(combatant.id, this._getActionCombat(event))
      }
      else {
        ui.notifications.info("Impossible de lancer l'initiative sans être dans un combat.")
      }
    })

    this.html.find(".button-tmr").click(async event => await this.actor.displayTMR("normal"))
    this.html.find(".button-tmr-rapide").click(async event => await this.actor.displayTMR("rapide"))

    this.html.find(".button-repos").click(async event => await this.actor.repos())

    this.html.find(".carac-xp-augmenter").click(async event =>
      await this.actor.updateCaracXPAuto(event.currentTarget.name.replace("augmenter.", ""))
    )
    this.html.find(".competence-xp-augmenter").click(async event =>
      await this.actor.updateCompetenceXPAuto(RdDSheetUtility.getItemId(event))
    )
    this.html.find(".competence-stress-augmenter").click(async event => {
      await this.actor.updateCompetenceStress(RdDSheetUtility.getItemId(event))
      this.render({ force: true })
    })

    if (this.vueDetaillee) {
      this.html.find("input.carac-xp").change(async event => {
        const caracName = event.currentTarget.name.replace(".xp", "").replace("system.carac.", "")
        await this.actor.updateCaracXP(caracName, parseInt(event.target.value))
      })
      this.html.find("input.competence-xp").change(async event => {
        const compName = event.currentTarget.attributes.compname.value
        await this.actor.updateCompetenceXP(compName, parseInt(event.target.value))
      })
      this.html.find("input.competence-xp-sort").change(async event => {
        const compName = event.currentTarget.attributes.compname.value
        await this.actor.updateCompetenceXPSort(compName, parseInt(event.target.value))
      })

      this.html.find(".toggle-archetype").click(async event => {
        this.vueArchetype = !this.vueArchetype
        this.render({ force: true })
      })
      this.html.find(".competence-archetype").change(async event => {
        const compName = event.currentTarget.attributes.compname.value
        await this.actor.updateCompetenceArchetype(compName, parseInt(event.target.value))
      })
      this.html.find(".nouvelle-incarnation").click(async event => await this.actor.nouvelleIncarnation())
      this.html.find(".repartition-archetype-aleatoire").click(async event => await this.actor.repartitionArchetypeAleatoire())
    }

    this.html.find(".pointsreve-value").change(async event =>
      await this.actor.update({ "system.reve.reve.value": event.currentTarget.value })
    )
    this.html.find(".seuil-reve-value").change(async event =>
      await this.actor.update({ "system.reve.seuil.value": event.currentTarget.value })
    )

    this.html.find(".stress-test").click(async event => await this.actor.transformerStress())
    this.html.find(".moral-malheureux").click(async event => await this.actor.jetDeMoral(MORAL.MALHEUREUX))
    this.html.find(".moral-neutre").click(async event => await this.actor.jetDeMoral(MORAL.NEUTRE))
    this.html.find(".moral-heureux").click(async event => await this.actor.jetDeMoral(MORAL.HEUREUX))
    this.html.find(".button-ethylisme").click(async event => await this.actor.jetEthylisme())
    this.html.find(".btn-sust-externe").click(async event => await this.actor.mangerExterne())
    this.html.find(".btn-sust-rations").click(async event => await this.actor.mangerRations())

    this.html.find(".ptreve-actuel-plus").click(async event => await this.actor.reveActuelIncDec(1))
    this.html.find(".ptreve-actuel-moins").click(async event => await this.actor.reveActuelIncDec(-1))
    this.html.find(".chance-actuelle-plus").click(async event => await this.actor.chanceActuelleIncDec(1))
    this.html.find(".chance-actuelle-moins").click(async event => await this.actor.chanceActuelleIncDec(-1))
    this.html.find(".fatigue-plus").click(async event => await this.actor.santeIncDec("fatigue", 1))
    this.html.find(".fatigue-moins").click(async event => await this.actor.santeIncDec("fatigue", -1))
  }

  _getBlessure(event) {
    const blessureId = this.html.find(event.currentTarget).parents(".item-blessure").data("item-id")
    return this.actor.getItem(blessureId, "blessure")
  }

  isCompetenceAffichable(competence) {
    return !this.showCompNiveauBase || !RdDItemCompetence.isNiveauBase(competence)
  }

  async _onDropActor(event, dragData) {
    const dropActor = fromUuidSync(dragData.uuid)
    this.actor.addSubActeur(dropActor)
    await super._onDrop(event, dragData)
  }

  _openSubActeur(actorId) {
    game.actors.get(actorId)?.sheet.render({ force: true })
  }

  _deleteSubActeur(actorId, li) {
    if (actorId) {
      const subActor = game.actors.get(actorId)
      RdDUtility.confirmSubActeurDelete(this, subActor, li, () => {
        console.log("Delete : ", subActor.id)
        this.actor.deleteSubActeur(subActor.id)
        RdDUtility.slideOnDelete(this, li)
      })
    }
  }

  async _selectTypeOeuvreToCreate() {
    const types = RdDItem.getTypesOeuvres()
    let content = `<span class="generic-label">Selectionnez le type d'oeuvre</span><select class="item-type">`
    for (const typeName of types) {
      content += `<option value="${typeName}">${Misc.typeName("Item", typeName)}</option>`
    }
    content += "</select>"
    new foundry.applications.api.DialogV2({
      title: "Créer une oeuvre",
      content,
      buttons: [
        { action: "create", label: "Créer l'oeuvre", icon: "fa-solid fa-check", callback: () => this.actor.createItem($(".item-type").val()) },
      ],
    }).render({ force: true })
  }

  async _createEmptyTache() {
    await this.actor.createItem(ITEM_TYPES.tache, "Nouvelle tache")
  }

  _getActionCombat(event) {
    const li = this.html.find(event.currentTarget)?.parents(".item")
    const armeName = li.data("arme-name")
    const compName = li.data("competence-name")
    const arme = this.armesList.find(a => a.arme.name == armeName && a.comp.name == compName)
    if (!arme) {
      return {
        name: armeName,
        arme: { name: armeName },
        comp: { name: compName },
      }
    }
    return arme
  }

  async splitItem(item) {
    const dialog = await DialogSplitItem.create(item, (it, split) => this._onSplitItem(it, split))
    dialog.render({ force: true })
  }

  async _onSplitItem(item, split) {
    if (split >= 1 && split < item.system.quantite) {
      await item.diminuerQuantite(split)
      const splitItem = foundry.utils.deepClone(item)
      splitItem.system.quantite = split
      await this.actor.createEmbeddedDocuments("Item", [splitItem])
    }
  }
}
