const { HandlebarsApplicationMixin } = foundry.applications.api

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

  #dragDrop

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-les-heritiers", "item"],
    position: {
      width: 620,
      height: 600,
    },
    form: {
      submitOnChange: true,
    },
    window: {
      resizable: true,
    },
    tabs: [
      {
        navSelector: 'nav[data-group="primary"]',
        contentSelector: "section.sheet-body",
        initial: "description",
      },
    ],
    dragDrop: [{ dragSelector: "[data-drag]", dropSelector: null }],
    actions: {
      editImage: HeritiersItemSheet.#onEditImage,
      postItem: HeritiersItemSheet.#onPostItem,
    },
  }

  /**
   * Tab groups state
   * @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 }),
      isEditMode: true,
      isEditable: this.isEditable,
      isGM: game.user.isGM,
      config: CONFIG.HERITIERS,
    }
    return context
  }

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

    // Activate tab navigation manually
    const nav = this.element.querySelector('nav.tabs[data-group]')
    if (nav) {
      const group = nav.dataset.group
      // Activate the current tab
      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()
        })
      })

      // Show/hide tab content
      this.element.querySelectorAll('[data-group="' + group + '"][data-tab]').forEach(content => {
        content.classList.toggle('active', content.dataset.tab === activeTab)
      })
    }
  }

  // #region Drag-and-Drop Workflow
  /**
   * Create drag-and-drop workflow handlers for this Application
   * @returns {DragDrop[]}     An array of DragDrop handlers
   * @private
   */
  #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(d)
    })
  }

  /**
   * Can the User start a drag workflow for a given drag selector?
   * @param {string} selector       The candidate HTML selector for the drag event
   * @returns {boolean}             Can the current user drag this selector?
   * @protected
   */
  _canDragStart(selector) {
    return this.isEditable
  }

  /**
   * Can the User drop an entry at a given drop selector?
   * @param {string} selector       The candidate HTML selector for the drop event
   * @returns {boolean}             Can the current user drop on this selector?
   * @protected
   */
  _canDragDrop(selector) {
    return this.isEditable
  }

  /**
   * Callback for dragstart events.
   * @param {DragEvent} event       The drag start event
   * @protected
   */
  _onDragStart(event) {
    const target = event.currentTarget
    const dragData = { type: "Item", uuid: this.document.uuid }
    event.dataTransfer.setData("text/plain", JSON.stringify(dragData))
  }

  /**
   * Callback for dragover events.
   * @param {DragEvent} event       The drag over event
   * @protected
   */
  _onDragOver(event) {
    // Default behavior is fine
  }

  /**
   * Callback for drop events.
   * @param {DragEvent} event       The drop event
   * @protected
   */
  async _onDrop(event) {
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)
    const item = await fromUuid(data.uuid)
    if (!item) return

    console.log("Item dropped:", item)
  }
  // #endregion

  // #region Action Handlers
  /**
   * Edit the item image
   * @param {Event} event       The triggering event
   * @param {HTMLElement} target    The target element
   * @private
   */
  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()
  }

  /**
   * Post item to chat
   * @param {Event} event       The triggering event
   * @param {HTMLElement} target    The target element
   * @private
   */
  static async #onPostItem(event, target) {
    let chatData = foundry.utils.duplicate(this.document)
    if (this.document.actor) {
      chatData.actor = { id: this.document.actor.id }
    }
    // Don't post any image for the item if the default image is used
    if (chatData.img.includes("/blank.png") || chatData.img.includes("/mystery-man")) {
      chatData.img = null
    }
    // JSON object for easy creation
    chatData.jsondata = JSON.stringify({
      compendium: "postedItem",
      payload: chatData,
    })

    const html = await renderTemplate('systems/fvtt-les-heritiers/templates/post-item.html', chatData)
    const chatOptions = {
      user: game.user.id,
      content: html,
    }
    ChatMessage.create(chatOptions)
  }

  // #endregion
}
