const { HandlebarsApplicationMixin } = foundry.applications.api

import { LesOubliesUtility } from "../../les-oublies-utility.js"

export default class LesOubliesItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  static SHEET_MODES = { EDIT: 0, PLAY: 1 }

  static DEFAULT_OPTIONS = {
    classes: ["fvtt-les-oublies", "sheet", "item"],
    position: {
      width: 760,
      height: 720,
    },
    window: {
      resizable: true,
    },
    form: {
      submitOnChange: true,
      closeOnSubmit: false,
    },
    actions: {
      toggleSheet: LesOubliesItemSheet.#onToggleSheet,
      editImage: LesOubliesItemSheet.#onEditImage,
    },
  }

  _sheetMode = this.constructor.SHEET_MODES.EDIT

  get isEditMode() {
    return this._sheetMode === this.constructor.SHEET_MODES.EDIT
  }

  get isPlayMode() {
    return this._sheetMode === this.constructor.SHEET_MODES.PLAY
  }

  async _prepareContext() {
    const config = CONFIG.LESOUBLIES
    const enriched = await LesOubliesUtility.prepareEnrichedHtml("Item", this.document.type, this.document.system)
    const skillLabels = Object.fromEntries(Object.entries(config.skills).map(([key, skill]) => [key, skill.label]))
    const choiceSets = {
      profileOptions: config.profiles.map((profile) => ({ value: profile.id, label: profile.label })),
      skillOptions: LesOubliesUtility.createChoices(Object.keys(config.skills), skillLabels),
      spellSkillOptions: LesOubliesUtility.createChoices(["magie", "onirologie", "chimerisme"], skillLabels),
      weaponCategoryOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.weaponCategoryLabels), config.weaponCategoryLabels),
        this.document.system.category,
      ),
      weaponOriginOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.weaponOriginLabels), config.weaponOriginLabels),
        this.document.system.origin,
      ),
      armorStateOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.armorStateLabels), config.armorStateLabels),
        this.document.system.state,
      ),
      equipmentCategoryOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.equipmentCategoryLabels), config.equipmentCategoryLabels),
        this.document.system.category,
      ),
      spellTraditionOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.spellTraditionLabels), config.spellTraditionLabels),
        this.document.system.tradition,
      ),
      polarityOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.polarityLabels), config.polarityLabels),
        this.document.system.polarity,
      ),
      stackingOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.stackingLabels), config.stackingLabels),
        this.document.system.stacking,
      ),
      companyPowerScopeOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.companyPowerScopeLabels), config.companyPowerScopeLabels),
        this.document.system.scope,
      ),
      companyPowerModeOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createChoices(Object.keys(config.companyPowerModeLabels), config.companyPowerModeLabels),
        this.document.system.effectMode,
      ),
      raceSizeOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.createRangeChoices(1, 4, config.sizes),
        this.document.system.size,
      ),
      mainRaceOptions: LesOubliesUtility.ensureChoice(
        LesOubliesUtility.sortByName(game.items.filter((item) => item.type === "race")).map((item) => ({
          value: item.name,
          label: item.name,
        })),
        this.document.system.mainRace,
      ),
    }

    return {
      item: this.document,
      system: this.document.system,
      source: this.document.toObject(),
      fields: this.document.schema.fields,
      systemFields: this.document.system.schema.fields,
      isEditable: this.isEditable,
      isEditMode: this.isEditMode,
      isPlayMode: this.isPlayMode,
      isGM: game.user.isGM,
      config,
      choiceSets,
      enriched,
      enrichedDescription: foundry.utils.getProperty(enriched, "description") ?? "",
      weaponDamagePreview: this.document.type === "arme"
        ? LesOubliesUtility.formatWeaponDamage(this.document.parent instanceof Actor ? this.document.parent : null, this.document)
        : "",
    }
  }

  static #onToggleSheet() {
    const modes = this.constructor.SHEET_MODES
    this._sheetMode = this.isEditMode ? modes.PLAY : modes.EDIT
    this.render()
  }

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