import { TeDeumUtility } from "../common/tedeum-utility.js";

const { HandlebarsApplicationMixin } = foundry.applications.api

/**
 * Feuille d'item Te Deum - AppV2
 */
export class TeDeumItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-te-deum", "sheet", "item"],
    position: {
      width: 620,
      height: 580,
    },
    form: {
      submitOnChange: true,
      closeOnSubmit: false,
    },
    window: {
      resizable: true,
    },
    actions: {
      editImage: TeDeumItemSheet.#onEditImage,
      postItem: TeDeumItemSheet.#onPostItem,
      deleteSubitem: TeDeumItemSheet.#onDeleteSubitem,
      viewSubitem: TeDeumItemSheet.#onViewSubitem,
    },
  }

  // Static PARTS pointing to the dynamic wrapper template
  static PARTS = {
    sheet: { template: "systems/fvtt-te-deum/templates/items/item-sheet.hbs" },
  }

  tabGroups = { primary: "description" }

  /* -------------------------------------------- */
  /** @override */
  async _prepareContext() {
    const item = this.document
    const TextEditor = foundry.applications.ux.TextEditor.implementation
    const enrich = async (val) => val !== undefined ? await TextEditor.enrichHTML(val ?? "", { async: true }) : ""
    const context = {
      title: this.title,
      id: item.id,
      type: item.type,
      img: item.img,
      name: item.name,
      editable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      system: foundry.utils.duplicate(item.system),
      systemFields: item.system.schema.fields,
      config: foundry.utils.duplicate(game.system.tedeum.config),
      competences: TeDeumUtility.getCompetencesForDropDown(),
      limited: item.limited,
      owner: item.isOwner,
      enrichedDescription: await enrich(item.system.description),
      enrichedTransmission: await enrich(item.system.transmission),
      enrichedSymptomes: await enrich(item.system.symptomes),
      enrichedComplications: await enrich(item.system.complications),
      enrichedVertus: await enrich(item.system.vertus),
      enrichedToxicite: await enrich(item.system.toxicite),
      isGM: game.user.isGM,
      itemPartialName: `systems/fvtt-te-deum/templates/items/item-${item.type}-sheet.hbs`,
    }
    if (item.type === "education") {
      TeDeumUtility.prepareEducationContent(context)
    }
    return context
  }

  /* -------------------------------------------- */
  /** @override */
  _onRender(context, options) {
    super._onRender(context, options)

    // Tab navigation
    const nav = this.element.querySelector('nav.tabs[data-group]')
    if (nav) {
      const group = nav.dataset.group
      const activeTab = this.tabGroups[group] || "description"
      nav.querySelectorAll('[data-tab]').forEach(link => {
        const tab = link.dataset.tab
        link.classList.toggle('active', tab === activeTab)
        link.addEventListener('click', event => {
          event.preventDefault()
          this.tabGroups[group] = tab
          this.render()
        })
      })
      this.element.querySelectorAll(`[data-group="${group}"][data-tab]`).forEach(content => {
        content.classList.toggle('active', content.dataset.tab === activeTab)
      })
    }

    // Ignore Enter key in inputs
    this.element.addEventListener('keydown', e => {
      if (e.keyCode === 13 && e.target.tagName !== 'TEXTAREA') e.preventDefault()
    })
  }

  // #region Static action handlers

  static async #onEditImage(event, target) {
    const fp = new FilePicker({
      type: "image",
      current: this.document.img,
      callback: path => this.document.update({ img: path }),
    })
    fp.browse()
  }

  static async #onPostItem(event, target) {
    const chatData = foundry.utils.duplicate(this.item)
    if (this.actor) {
      chatData.actor = { id: this.actor.id }
    }
    if (chatData.img?.includes("/blank.png")) {
      chatData.img = null
    }
    chatData.jsondata = JSON.stringify({ compendium: "postedItem", payload: chatData })
    const html = await foundry.applications.handlebars.renderTemplate(
      'systems/fvtt-te-deum/templates/post-item.html', chatData
    )
    ChatMessage.create(TeDeumUtility.chatDataSetup(html))
  }

  static async #onDeleteSubitem(event, target) {
    const field = target.dataset.type
    const idx = parseInt(target.dataset.index)
    const oldArray = this.document.system[field]
    if (Array.isArray(oldArray) && oldArray[idx]?.name !== 'None') {
      const newArray = oldArray.filter((_, i) => i !== idx)
      this.document.update({ [`system.${field}`]: newArray })
    }
  }

  static async #onViewSubitem(event, target) {
    const li = target.closest(".item")
    const levelIndex = parseInt(li?.dataset.levelIndex)
    const choiceIndex = parseInt(li?.dataset.choiceIndex)
    const featureId = li?.dataset.featureId
    const itemData = this.document.system.levels?.[levelIndex]?.choices?.[choiceIndex]?.features?.[featureId]
    if (itemData?.name !== 'None') {
      const item = await Item.create(itemData, { temporary: true })
      item.system.origin = "embeddedItem"
      new TeDeumItemSheet(item).render(true)
    }
  }

  // #endregion
}