const { HandlebarsApplicationMixin } = foundry.applications.api

export default class MaleficesItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  constructor(options = {}) {
    super(options)
    this.#dragDrop = this.#createDragDropHandlers()
  }

  #dragDrop

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-malefices", "item"],
    position: {
      width: 620,
      height: 600,
    },
    form: {
      submitOnChange: true,
    },
    window: {
      resizable: true,
    },
    dragDrop: [{ dragSelector: "[data-drag]", dropSelector: null }],
    actions: {
      editImage: MaleficesItemSheet.#onEditImage,
      postItem: MaleficesItemSheet.#onPostItem,
    },
  }

  /** @type {object} */
  tabGroups = { primary: "description" }

  /** @override */
  async _prepareContext() {
    const context = {
      fields: this.document.schema.fields,
      systemFields: this.document.system.schema.fields,
      item: this.document,
      system: this.document.system,
      source: this.document.toObject(),
      enrichedDescription: await foundry.applications.ux.TextEditor.implementation.enrichHTML(
        this.document.system.description ?? "", { async: true }
      ),
      isEditable: this.isEditable,
      cssClass: this.isEditable ? "editable" : "locked",
      isGM: game.user.isGM,
      config: game.system.malefices.config,
    }
    return context
  }

  /** @override */
  _onRender(context, options) {
    super._onRender(context, options)
    this.#dragDrop.forEach((d) => d.bind(this.element))

    // Manual 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)
      })
    }
  }

  // #region Drag-and-Drop
  #createDragDropHandlers() {
    return this.options.dragDrop.map((d) => {
      d.permissions = {
        dragstart: this._canDragStart.bind(this),
        drop: this._canDragDrop.bind(this),
      }
      d.callbacks = {
        dragstart: this._onDragStart.bind(this),
        dragover: this._onDragOver.bind(this),
        drop: this._onDrop.bind(this),
      }
      return new foundry.applications.ux.DragDrop.implementation(d)
    })
  }

  _canDragStart(selector) { return this.isEditable }
  _canDragDrop(selector) { return this.isEditable }

  _onDragStart(event) {
    const dragData = { type: "Item", uuid: this.document.uuid }
    event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
  }

  _onDragOver(event) {}

  async _onDrop(event) {}
  // #endregion

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

  static async #onPostItem(event, target) {
    let chatData = foundry.utils.duplicate(this.document)
    if (this.document.actor) {
      chatData.actor = { id: this.document.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-malefices/templates/post-item.hbs', chatData
    )
    ChatMessage.create({ user: game.user.id, content: html })
  }
  // #endregion
}
