import { SYSTEM } from "../../config/system.mjs"
import { buildSharedSelectOptions } from "./select-options.mjs"
import { enrichHTMLFields } from "./rich-text.mjs"

const { HandlebarsApplicationMixin } = foundry.applications.api

export default class MGNEActorSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {
  static DEFAULT_OPTIONS = {
    classes: ["mgne", "actor-sheet"],
    position: {
      width: 900,
      height: "auto",
    },
    window: {
      resizable: true,
    },
    form: {
      submitOnChange: true,
    },
    actions: {
      editImage: MGNEActorSheet.onEditImage,
      changeTab: MGNEActorSheet.onChangeTab,
      createItem: MGNEActorSheet.onCreateItem,
      editItem: MGNEActorSheet.onEditItem,
      deleteItem: MGNEActorSheet.onDeleteItem,
      toggleEquipped: MGNEActorSheet.onToggleEquipped,
      syncArtifact: MGNEActorSheet.onSyncArtifact,
      resetDaily: MGNEActorSheet.onResetDaily,
      rollResonancePerDay: MGNEActorSheet.onRollResonancePerDay,
      clearResonationBlock: MGNEActorSheet.onClearResonationBlock,
      quickRest: MGNEActorSheet.onQuickRest,
      fullRest: MGNEActorSheet.onFullRest,
    },
  }

  async _prepareContext() {
    const systemFields = this.document.system.schema.fields

    return {
      fields: this.document.schema.fields,
      systemFields,
      actor: this.document,
      system: this.document.system,
      source: this.document.toObject(),
      config: SYSTEM,
      enrichedFields: await enrichHTMLFields(this.document.system, systemFields),
      isEditable: this.isEditable,
      selectOptions: buildSharedSelectOptions(),
    }
  }

  _onRender(context, options) {
    super._onRender?.(context, options)
    this.element.querySelectorAll(".rollable").forEach(element => {
      element.addEventListener("click", this._onRoll.bind(this))
    })
  }

  async _onRoll(event) {
    const target = event.currentTarget
    const itemId = target.closest("[data-item-id]")?.dataset.itemId
    const rollType = target.dataset.rollType

    switch (rollType) {
      case "ability":
        return this.document.rollAbility(target.dataset.abilityId)
      case "defense":
        return this.document.rollDefense()
      case "weapon":
        return this.document.rollWeapon(itemId)
      case "profile-attack":
        return this.document.rollProfileAttack()
      case "profile-damage":
        return this.document.rollProfileDamage()
      case "damage":
        return this.document.rollDamage(itemId)
      case "resonation":
        return this.document.rollResonation(itemId)
      case "morale":
        return this.document.rollMorale()
      case "usage":
        return this.document.rollUsage(itemId)
      default:
        return null
    }
  }

  static async onEditImage(_event, target) {
    const attr = target.dataset.edit
    const current = foundry.utils.getProperty(this.document, attr)
    const picker = new FilePicker({
      current,
      type: "image",
      callback: path => this.document.update({ [attr]: path }),
      top: this.position.top + 40,
      left: this.position.left + 10,
    })
    return picker.browse()
  }

  static onChangeTab(_event, target) {
    const group = target.dataset.group
    const tab = target.dataset.tab
    this.tabGroups[group] = tab
    this.render()
  }

  static async onCreateItem(_event, target) {
    const itemType = target.dataset.itemType
    const typeLabel = SYSTEM.itemTypes[itemType]?.label ?? itemType
    const [created] = await this.document.createEmbeddedDocuments("Item", [{
      name: game.i18n.format("MGNE.Common.NewItem", { type: typeLabel }),
      type: itemType,
      img: SYSTEM.itemTypes[itemType]?.icon,
    }])
    created?.sheet?.render(true)
  }

  static async onEditItem(_event, target) {
    const itemId = target.closest("[data-item-id]")?.dataset.itemId
    const item = this.document.items.get(itemId)
    return item?.sheet?.render(true)
  }

  static async onDeleteItem(_event, target) {
    const itemId = target.closest("[data-item-id]")?.dataset.itemId
    const item = this.document.items.get(itemId)
    if (!item) return null
    return item.delete()
  }

  static async onToggleEquipped(_event, target) {
    const itemId = target.closest("[data-item-id]")?.dataset.itemId
    return this.document.toggleItemEquipped(itemId)
  }

  static async onSyncArtifact(_event, target) {
    const itemId = target.closest("[data-item-id]")?.dataset.itemId
    return this.document.syncArtifact(itemId)
  }

  static async onResetDaily() {
    return this.document.resetDaily()
  }

  static async onRollResonancePerDay() {
    return this.document.rollResonancePerDay()
  }

  static async onClearResonationBlock() {
    return this.document.update({ "system.resonance.blocked": false })
  }

  static async onQuickRest() {
    return this.document.quickRest()
  }

  static async onFullRest() {
    return this.document.fullRest()
  }
}
