const { HandlebarsApplicationMixin } = foundry.applications.api

import { RdDUtility } from "../../rdd-utility.js"
import { Misc } from "../../misc.js"
import { DialogSplitItem } from "../../dialog-split-item.js"
import { RdDSheetUtility } from "../../rdd-sheet-utility.js"
import { Monnaie } from "../../item-monnaie.js"
import { ITEM_TYPES } from "../../constants.js"
import { RdDItem } from "../../item.js"
import { RdDTextEditor } from "../../apps/rdd-text-roll-editor.js"
import { ItemAction } from "../../item/item-actions.js"
import { DialogVerifierIngredients } from "../../dialog-verifier-ingredients.js"
import { DialogLancerRecette } from "../../dialog-lancer-recette.js"
import { ChatUtility } from "../../chat-utility.js"
import { RdDItemBlessure } from "../../item/blessure.js"
import { Grammar } from "../../grammar.js"
import { SYSTEM_RDD } from "../../constants.js"

export class RdDBaseActorSheetV2 extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {

  get actor() { return this.document }

  // Was this.options.* — custom state
  vueDetaillee = false
  triEquipement = "name"
  recherche = undefined

  static TYPE = undefined

  static DEFAULT_OPTIONS = {
    classes: ["rdd", "sheet", "actor"],
    position: { width: 640 },
    form: { submitOnChange: true, closeOnSubmit: false },
    window: { resizable: true, controls: [] },
    actions: {
      postToChat: RdDBaseActorSheetV2._onPostToChat,
    },
  }

  //#region Registration

  static register() {
    foundry.documents.collections.Actors.registerSheet(SYSTEM_RDD, this, {
      types: [this.TYPE],
      makeDefault: true,
    })
  }

  static async registerAll(...sheetClasses) {
    const handlebars = []
    sheetClasses.forEach(sheetClass => {
      if (sheetClass.PARTS) {
        Object.values(sheetClass.PARTS).forEach(part => {
          if (part.template) handlebars.push(part.template)
        })
      }
      sheetClass.register()
    })
    await foundry.applications.handlebars.loadTemplates(Misc.distinct(handlebars))
  }

  //#endregion

  //#region Data

  async _prepareContext() {
    Monnaie.validerMonnaies(this.actor)
    this.actor.computeEtatGeneral()

    this._sheetOptions = foundry.utils.mergeObject(
      RdDSheetUtility.mergeDocumentRights({ ...this.options }, this.actor, this.isEditable),
      { vueDetaillee: this.vueDetaillee, triEquipement: this.triEquipement, recherche: this.recherche },
      { inplace: false }
    )
    const ctx = {
      title: this.title,
      id: this.actor.id,
      type: this.actor.type,
      img: this.actor.img,
      name: this.actor.name,
      system: this.actor.system,
      systemFields: this.actor.system.schema.fields,
      description: await RdDTextEditor.enrichHTML(this.actor.system.description, this.actor),
      notesmj: await RdDTextEditor.enrichHTML(this.actor.system.notesmj, this.actor),
      options: this._sheetOptions,
      effects: this.actor.effects,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      limited: this.actor.limited,
      owner: this.actor.isOwner,
    }

    RdDUtility.filterItemsPerTypeForSheet(ctx, this.actor.itemTypes, this.triEquipement)
    ctx.calc = {
      fortune: Monnaie.toSolsDeniers(this.actor.getFortune()),
      prixTotalEquipement: this.actor.computePrixTotalEquipement(),
      encTotal: this.actor.getEncTotal(),
    }

    this.objetVersConteneur = RdDUtility.buildArbreDeConteneurs(ctx.conteneurs, ctx.inventaires)
    this._appliquerRechercheObjets(ctx.conteneurs, ctx.inventaires)
    ctx.conteneurs = RdDUtility.conteneursRacine(ctx.conteneurs)
    ctx.competences.filter(it => it.type == ITEM_TYPES.competencecreature)
      .forEach(it => it.isdommages = it.isDommages())

    return ctx
  }

  _appliquerRechercheObjets(conteneurs, inventaires) {
    if (this.recherche?.text) {
      const recherche = this.recherche
      const allVisible = inventaires.filter(it => it.isNomTypeLike(recherche.text)).map(it => it.id)
      let addVisible = conteneurs.filter(it => it.isNomTypeLike(recherche.text)).map(it => it.id)
      do {
        allVisible.push(...addVisible)
        const parentsIds = conteneurs.filter(it => it.system.contenu.find(id => allVisible.includes(id))).map(it => it.id)
        addVisible = parentsIds.filter(id => !allVisible.includes(id))
      }
      while (addVisible.length > 0)
      inventaires.forEach(it => it.system.isHidden = !allVisible.includes(it.id))
      conteneurs.forEach(it => it.system.isHidden = !allVisible.includes(it.id))
    }
    else {
      inventaires.forEach(it => it.system.isHidden = false)
      conteneurs.forEach(it => it.system.isHidden = false)
    }
  }

  //#endregion

  //#region Rendering

  async _renderFrame(options) {
    const frame = await super._renderFrame(options)
    return frame
  }

  async _onRender(context, options) {
    await super._onRender(context, options)
    this.html = $(this.element)

    const nav = this.element.querySelector(".sheet-tabs")
    if (nav) {
      const tab = this.tabGroups?.primary || nav.querySelector("[data-tab]")?.dataset.tab
      if (tab) this.changeTab(tab, "primary", { force: true })
    }

    this.html.find(".actionItem").click(async event => await ItemAction.onActionItem(event, this.actor, this._sheetOptions))
    this.html.find(".item-edit").click(async event => await this._onItemEdit(event))
    this.html.find(".item-verify-ingredients").click(async event => await this._onVerifyIngredients(event))
    this.html.find(".item-lancer-recette").click(async event => await this._onLancerRecette(event))
    this.html.find(".conteneur-name a").click(async event => {
      RdDUtility.toggleAfficheContenu(this._getItemId(event))
      this.render({ force: true })
    })

    this.html.find(".actor-montrer").click(async event => await this.actor.postActorToChat())

    this.html.find(".recherche")
      .each((_index, field) => this._rechercheSelectArea(field))
      .keyup(async event => this._rechercherKeyup(event))
      .change(async event => this._rechercherKeyup(event))

    this.html.find(".recherche").prop("disabled", false)

    this.html.find(".item-list .item").dblclick(async event => {
      const item = this._getItem(event)
      if (item) item.sheet.render({ force: true })
    })

    this.html.find(".tri-equipement").change(event => {
      this.triEquipement = event.currentTarget.value
      this.render({ force: true })
    })

    if (!this.isEditable) return

    this.html.find(".item-equip-armure").click(async event => await this.actor.equiperObjet(this._getItem(event)))
    this.html.find(".item-delete").click(async event => await RdDUtility.confirmActorItemDelete(this._getItem(event), this.actor))
    this.html.find(".item-quantite-plus").click(async event => await this.actor.itemQuantiteIncDec(this._getItemId(event), 1))
    this.html.find(".item-quantite-moins").click(async event => await this.actor.itemQuantiteIncDec(this._getItemId(event), -1))
    this.html.find(".item-quantite").change(async event => {
      const input = event.currentTarget
      const item = this.actor.items.get(input.dataset.itemId)
      if (item) {
        const newQty = Math.max(0, parseInt(input.value) || 0)
        await item.update({ "system.quantite": newQty })
        if (newQty === 0) this.render({ force: true })
      }
    })
    this.html.find(".item-quantite").on("contextmenu", async event => {
      event.preventDefault()
      const item = this._getItem(event)
      if (!item?.isInventaire()) return
      new foundry.applications.api.DialogV2({
        title: `Quantité — ${item.name}`,
        content: `<p>Réduire la quantité de :</p>
          <select class="qty-amount">
            <option value="1">1</option>
            <option value="5">5</option>
            <option value="10">10</option>
            <option value="all">Tout jeter</option>
          </select>`,
        buttons: [
          { action: "reduce", label: "Retirer", icon: "fa-solid fa-minus", callback: (event, button, dialog) => {
            const amount = dialog.element.querySelector(".qty-amount").value
            if (amount === "all") {
              item.delete()
              this.render({ force: true })
            } else {
              item.update({ "system.quantite": Math.max(0, item.system.quantite - parseInt(amount)) })
            }
          }},
        ],
      }).render({ force: true })
    })

    this.html.find(".creer-un-objet").click(async event => await this._selectObjetTypeToCreate())
    this.html.find(".nettoyer-conteneurs").click(async event => await this.actor.nettoyerConteneurs())
    this.html.find(".quick-add-ration").click(async event => {
      const existante = this.actor.items.find(it => it.type === "nourritureboisson" && it.name === "Ration")
      if (existante) {
        await existante.update({ "system.quantite": Math.max(0, Number(existante.system.quantite) + 1) })
      } else {
        await this.actor.createEmbeddedDocuments("Item", [{
          name: "Ration", type: "nourritureboisson",
          img: "systems/foundryvtt-reve-de-dragon/icons/objets/provision_crue.webp",
          system: { sust: 1, encombrement: 0.1, quantite: 1, cout: 0.1, boisson: false },
        }], { renderSheet: false })
      }
      this.render({ force: true })
    })
    this.html.find(".quick-add-eau").click(async event => {
      const existante = this.actor.items.find(it => it.type === "nourritureboisson" && it.name === "Eau")
      if (existante) {
        await existante.update({ "system.quantite": Math.max(0, Number(existante.system.quantite) + 1) })
      } else {
        await this.actor.createEmbeddedDocuments("Item", [{
          name: "Eau", type: "nourritureboisson",
          img: "systems/foundryvtt-reve-de-dragon/icons/objets/outre.webp",
          system: { desaltere: 1, encombrement: 0.1, quantite: 1, cout: 0.05, boisson: true },
        }], { renderSheet: false })
      }
      this.render({ force: true })
    })

    this.html.find(".vue-detaillee").click(async event => {
      this.vueDetaillee = !this.vueDetaillee
      this.render({ force: true })
    })

    // Revel listeners (was base-actor-reve-sheet.js)
    this.html.find(".button-encaissement").click(async event => await this.actor.encaisser())
    this.html.find(".roll-carac").click(async event => {
      await this.actor.rollCarac(Grammar.toLowerCaseNoAccent(event.currentTarget.attributes["data-carac-name"].value))
    })
    this.html.find(".roll-competence").click(async event => await this.actor.rollCompetence(this._getItemId(event)))
    this.html.find(".endurance-plus").click(async event => await this.actor.santeIncDec("endurance", 1))
    this.html.find(".endurance-moins").click(async event => await this.actor.santeIncDec("endurance", -1))

    if (game.user.isGM) {
      this.html.find(".button-remise-a-neuf").click(async event => await this.actor.remiseANeuf())
      this.html.find(".delete-active-effect").click(async event => await this.actor.removeEffect(this.html.find(event.currentTarget).parents(".active-effect").data("effect")))
      this.html.find(".enlever-tous-effets").click(async event => await this.actor.removeEffects())
    }
    this.html.find(".competence-add").click(async event =>
      await this.actor.createEmbeddedDocuments("Item", [{
        type: ITEM_TYPES.competencecreature,
        name: "Nouvelle competence",
        img: "systems/foundryvtt-reve-de-dragon/icons/compcreature-serres.webp",
        system: { carac_value: this.actor.getForce() },
      }], { renderSheet: true })
    )
    this.html.find(".roll-text").click(async event => await RdDTextEditor.rollText(event, this.actor))
    this.html.find(".chat-roll-text").click(async event => await RdDTextEditor.chatRollText(event))

    if (this.vueDetaillee) {
      this.html.find(".carac-value").change(async event => {
        if (event.currentTarget.name.includes("carac.")) {
          const caracName = event.currentTarget.name.replace("carac.", "")
          await this.actor.updateCarac(caracName, parseInt(event.currentTarget.value))
        }
      })
      this.html.find(".competence-value").change(async event => {
        const compName = event.currentTarget.attributes.compname.value
        await this.actor.updateCompetence(compName, parseInt(event.currentTarget.value))
      })
    }

    // Sang listeners (was base-actor-sang-sheet.js)
    this.html.find(".creer-blessure-legere").click(async event => await RdDItemBlessure.createBlessure(this.actor, 2))
    this.html.find(".creer-blessure-grave").click(async event => await RdDItemBlessure.createBlessure(this.actor, 4))
    this.html.find(".creer-blessure-critique").click(async event => await RdDItemBlessure.createBlessure(this.actor, 6))
    this.html.find(".subir-blessure-contusion").click(async event => await RdDItemBlessure.applyFullBlessure(this.actor, 0))
    this.html.find(".subir-blessure-legere").click(async event => await RdDItemBlessure.applyFullBlessure(this.actor, 2))
    this.html.find(".subir-blessure-grave").click(async event => await RdDItemBlessure.applyFullBlessure(this.actor, 4))
    this.html.find(".subir-blessure-critique").click(async event => await RdDItemBlessure.applyFullBlessure(this.actor, 6))
    this.html.find(".jet-vie").click(async event => await this.actor.jetDeVie())
    this.html.find(".jet-endurance").click(async event => await this._jetEndurance())
    this.html.find(".vie-plus").click(async event => await this.actor.santeIncDec("vie", 1))
    this.html.find(".vie-moins").click(async event => await this.actor.santeIncDec("vie", -1))
  }

  async _jetEndurance() {
    const endurance = this.actor.getEnduranceActuelle()
    const result = await this.actor.jetEndurance(endurance)
    await ChatMessage.create({
      content: `Jet d'Endurance : ${result.jetEndurance} / ${endurance}
        <br>${this.actor.name} a ${result.sonne ? "échoué" : "réussi"} son Jet d'Endurance ${result.sonne ? "et devient Sonné" : ""}`,
      whisper: ChatUtility.getOwners(this.actor),
    })
  }

  _rechercherKeyup(event) {
    const currentTarget = event.currentTarget
    const nouvelleRecherche = this._optionRecherche(currentTarget)
    if (this.recherche?.text != nouvelleRecherche?.text) {
      this.recherche = nouvelleRecherche
      if (this._timerRecherche) clearTimeout(this._timerRecherche)
      this._timerRecherche = setTimeout(() => {
        this._timerRecherche = undefined
        this.render({ force: true })
      }, 500)
    }
  }

  _rechercheSelectArea(field) {
    if (this.recherche) {
      field.focus()
      field.setSelectionRange(this.recherche.start, this.recherche.end)
    }
  }

  _optionRecherche(target) {
    if (!target.value?.length) return undefined
    return {
      text: target.value,
      start: target.selectionStart,
      end: target.selectionEnd,
    }
  }

  //#endregion

  //#region Drop

  async _onDropItem(event, item) {
    const destItemId = this.html.find(event.target)?.closest(".item").attr("data-item-id")
    const previousItemIds = new Set(this.actor.items.keys())
    const dropParams = await RdDSheetUtility.prepareItemDropParameters(destItemId, this.actor, { uuid: item.uuid }, this.objetVersConteneur)
    if (dropParams) {
      const callSuper = await this.actor.processDropItem(dropParams)
      if (callSuper) {
        await super._onDropItem(event, item)
      }
      if (destItemId && dropParams.sourceActorId !== this.actor.id) {
        const container = this.actor.items.get(destItemId)
        if (container?.isConteneur()) {
          const dropped = [...this.actor.items].find(i => !previousItemIds.has(i.id))
          if (dropped && !this.actor.findConteneur(dropped)) {
            await this.actor.ajouterDansConteneur(dropped, container, () => {})
          }
        }
      }
    }
  }

  async _onDropActor(event, actor) {
    this.actor.addSubActeur(actor)
    await super._onDropActor(event, actor)
  }

  //#endregion

  //#region Helpers

  _getItemId(event) {
    return RdDSheetUtility.getItemId(event)
  }

  _getItem(event) {
    return RdDSheetUtility.getItem(event, this.actor)
  }

  async _onItemEdit(event) {
    const item = this._getItem(event)
    if (item) item.sheet.render({ force: true })
  }

  async _onVerifyIngredients(event) {
    event.preventDefault()
    const item = this._getItem(event)
    if (!item || item.type !== ITEM_TYPES.recettealchimique) return
    DialogVerifierIngredients.create(item, this.actor)
  }

  async _onLancerRecette(event) {
    event.preventDefault()
    const item = this._getItem(event)
    if (!item || item.type !== ITEM_TYPES.recettealchimique) return
    const ingredients = Misc.safeJsonParse(item.system.ingredients, [])
    if (!ingredients.length) {
      ui.notifications.warn("Cette recette n'a pas d'ingrédients définis.")
      return
    }
    DialogLancerRecette.create(item, this.actor)
  }

  //#endregion

  //#region Actions

  static async _onPostToChat(event, target) {
    await this.actor.postActorToChat()
  }

  //#endregion

  //#region Item operations

  async _selectObjetTypeToCreate() {
    const types = this._getTypesInventaire().sort(Misc.ascending(type => Misc.typeName("Item", type)))
    let content = `<span class="generic-label">Selectionnez le type d'équipement</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 un équipement",
      content,
      buttons: [
        { action: "create", label: "Créer l'objet", icon: "fa-solid fa-check", callback: () => this.actor.createItem($(".item-type").val()) },
      ],
    }).render({ force: true })
  }

  _getTypesInventaire() {
    return RdDItem.getItemTypesInventaire()
  }

  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])
    }
  }

  vendre(item) {
    item?.proposerVente(this.actor.getQuantiteDisponible(item))
  }

  //#endregion
}
