import CthulhuEternalActorSheet from "./base-actor-sheet.mjs"

export default class CthulhuEternalProtagonistSheet extends CthulhuEternalActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["protagonist"],
    position: {
      width: 860,
      height: 620,
    },
    window: {
      contentClasses: ["protagonist-content"],
    },
    actions: {
      setBP: CthulhuEternalProtagonistSheet.#onSetBP,
      toggleEquipped: CthulhuEternalProtagonistSheet.#onToggleEquipped,
      createGear: CthulhuEternalProtagonistSheet.#onCreateGear,
      createArmor: CthulhuEternalProtagonistSheet.#onCreateArmor,
      createWeapon: CthulhuEternalProtagonistSheet.#onCreateWeapon,
      createBond: CthulhuEternalProtagonistSheet.#onCreateBond,
      createInjury: CthulhuEternalProtagonistSheet.#onCreateInjury,
      createMentalDisorder: CthulhuEternalProtagonistSheet.#onCreateMentalDisorder,
      createMotivation: CthulhuEternalProtagonistSheet.#onCreateMotivation,
      createSkill: CthulhuEternalProtagonistSheet.#onCreateSkill,
      createRitual: CthulhuEternalProtagonistSheet.#onCreateRitual,
      createTome: CthulhuEternalProtagonistSheet.#onCreateTome,
    },
  }

  /** @override */
  static PARTS = {
    main: {
      template: "systems/fvtt-cthulhu-eternal/templates/protagonist-main.hbs",
    },
    tabs: {
      template: "templates/generic/tab-navigation.hbs",
    },
    skills: {
      template: "systems/fvtt-cthulhu-eternal/templates/protagonist-skills.hbs",
    },
    status: {
      template: "systems/fvtt-cthulhu-eternal/templates/protagonist-status.hbs",
    },
    equipment: {
      template: "systems/fvtt-cthulhu-eternal/templates/protagonist-equipment.hbs",
    },
    biography: {
      template: "systems/fvtt-cthulhu-eternal/templates/protagonist-biography.hbs",
    },
  }

  /** @override */
  tabGroups = {
    sheet: "skills",
  }

  /**
   * Prepare an array of form header tabs.
   * @returns {Record<string, Partial<ApplicationTab>>}
   */
  #getTabs() {
    const tabs = {
      skills: { id: "skills", group: "sheet", icon: "fa-solid fa-shapes", label: "CTHULHUETERNAL.Label.skills" },
      status: { id: "status", group: "sheet", icon: "fa-solid fa-file-waveform", label: "CTHULHUETERNAL.Label.status" },
      equipment: { id: "equipment", group: "sheet", icon: "fa-solid fa-shapes", label: "CTHULHUETERNAL.Label.equipment" },
      biography: { id: "biography", group: "sheet", icon: "fa-solid fa-book", label: "CTHULHUETERNAL.Label.biography" },
    }
    for (const v of Object.values(tabs)) {
      v.active = this.tabGroups[v.group] === v.id
      v.cssClass = v.active ? "active" : ""
    }
    return tabs
  }

  /** @override */
  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()

    context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.description, { async: true })
    context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.notes, { async: true })
    context.isGM = game.user.isGM

    context.tooltipsCharacteristic = {
      str: game.i18n.localize("CTHULHUETERNAL.Characteristic.Str"),
      dex: game.i18n.localize("CTHULHUETERNAL.Characteristic.Dex"),
      con: game.i18n.localize("CTHULHUETERNAL.Characteristic.Con"),
      int: game.i18n.localize("CTHULHUETERNAL.Characteristic.Int"),
      pow: game.i18n.localize("CTHULHUETERNAL.Characteristic.Pow"),
      cha: game.i18n.localize("CTHULHUETERNAL.Characteristic.Cha")
    }

    return context
  }

  /** @override */
  async _preparePartContext(partId, context) {
    const doc = this.document
    switch (partId) {
      case "main":
        break
      case "skills": {
        context.tab = context.tabs.skills
        let tmpSkills = doc.itemTypes.skill
        tmpSkills.sort((a, b) => a.name.localeCompare(b.name))
        const nbCols = 3;
        const nbRows = Math.ceil(tmpSkills.length / nbCols);
        let skillsColumns = Array.from({ length: nbRows }, (_, rowIdx) =>
          Array.from({ length: nbCols }, (_, colIdx) => tmpSkills[rowIdx + colIdx * nbRows]).filter(Boolean)
        );
        // Merge skillsColumns in a single flat array
        skillsColumns = skillsColumns.flat().filter(Boolean);
        //DEBUG : console.log("Skills columns:", skillsColumns);
        context.skills = skillsColumns
      }
        break
      case "equipment":
        context.tab = context.tabs.equipment
        context.weapons = doc.itemTypes.weapon
        context.weapons.sort((a, b) => a.name.localeCompare(b.name))
        context.armors = doc.itemTypes.armor
        context.armors.sort((a, b) => a.name.localeCompare(b.name))
        context.gears = doc.itemTypes.gear
        context.gears.sort((a, b) => a.name.localeCompare(b.name))
        context.rituals = doc.itemTypes.ritual
        context.rituals.sort((a, b) => a.name.localeCompare(b.name))
        context.tomes = doc.itemTypes.tome
        context.tomes.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "status":
        context.tab = context.tabs.status
        context.injuries = doc.itemTypes.injury
        context.injuries.sort((a, b) => a.name.localeCompare(b.name))
        context.mentaldisorders = doc.itemTypes.mentaldisorder
        context.mentaldisorders.sort((a, b) => a.name.localeCompare(b.name))
        context.motivations = doc.itemTypes.motivation
        context.motivations.sort((a, b) => a.name.localeCompare(b.name))
        context.bonds = doc.itemTypes.bond
        context.bonds.sort((a, b) => a.name.localeCompare(b.name))
        break
      case "biography":
        context.tab = context.tabs.biography
        context.enrichedDescription = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.description, { async: true })
        context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(doc.system.notes, { async: true })
        break
    }
    return context
  }

  /**
   * Creates a new attack item directly from the sheet and embeds it into the document.
   * @param {Event} event             The initiating click event.
   * @param {HTMLElement} target      The current target of the event listener.
   */
  static #onSetBP(event, target) {
    this.document.system.setBP()
  }

  static #onToggleEquipped(event, target) {
    const itemId = target.dataset.itemId
    const item = this.document.items.get(itemId)
    if (item) item.update({ "system.equipped": !item.system.equipped })
  }

  static #onCreateGear(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newGear"), type: "gear" }])
  }

  static #onCreateWeapon(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newWeapon"), type: "weapon" }])
  }

  static #onCreateArmor(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newArmor"), type: "armor" }])
  }

  static #onCreateBond(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newBond"), type: "bond" }])
  }

  static #onCreateInjury(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newInjury"), type: "injury" }])
  }

  static #onCreateMentalDisorder(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newMentalDisorder"), type: "mentaldisorder" }])
  }

  static #onCreateMotivation(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newMotivation"), type: "motivation" }])
  }

  static #onCreateSkill(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newSkill"), type: "skill" }])
  }

  static #onCreateRitual(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newRitual"), type: "ritual" }])
  }

  static #onCreateTome(event, target) {
    this.document.createEmbeddedDocuments("Item", [{ name: game.i18n.localize("CTHULHUETERNAL.Label.newTome"), type: "tome" }])
  }

  /**
   * Handles the roll action triggered by user interaction.
   *
   * @param {PointerEvent} event The event object representing the user interaction.
   * @param {HTMLElement} target The target element that triggered the roll.
   *
   * @returns {Promise<void>} A promise that resolves when the roll action is complete.
   *
   * @throws {Error} Throws an error if the roll type is not recognized.
   *
   * @description This method checks the current mode (edit or not) and determines the type of roll
   * (save, resource, or damage) based on the target element's data attributes. It retrieves the
   * corresponding value from the document's system and performs the roll.
   */
  async _onRoll(event, target) {
    let rollType = $(event.currentTarget).data("roll-type")
    let item
    let li
    // Debug : console.log(">>>>", event, target, rollType)
    // Deprecated : if (this.isEditMode) return
    switch (rollType) {
      case "resource":
        item = foundry.utils.duplicate(this.actor.system.resources)
        item.name = game.i18n.localize(`CTHULHUETERNAL.Label.Resources`)
        item.targetScore = item.permanentRating
        break
      case "char":
        let charId = $(event.currentTarget).data("char-id")
        item = foundry.utils.duplicate(this.actor.system.characteristics[charId])
        item.name = game.i18n.localize(`CTHULHUETERNAL.Label.${charId}Long`)
        item.targetScore = item.value * 5
        break
      case "skill":
        li = $(event.currentTarget).parents(".item");
        item = this.actor.items.get(li.data("item-id"));
        break
      case "weapon":
      case "damage":
        li = $(event.currentTarget).parents(".item");
        item = this.actor.items.get(li.data("item-id"));
        item.damageFormula = $(event.currentTarget).data("roll-value") || item.system.damage
        item.damageBonus = this.actor.system.damageBonus
        break
      case "san":
        item = foundry.utils.duplicate(this.actor.system.san)
        item.name = game.i18n.localize("CTHULHUETERNAL.Label.SAN")
        item.targetScore = item.value
        break;
      case "luck":
        item = foundry.utils.duplicate(this.actor.system.characteristics.int)
        item.name = game.i18n.localize("CTHULHUETERNAL.Label.Luck")
        item.value = 10
        item.targetScore = 50
        break;
      default:
        throw new Error(`Unknown roll type ${rollType}`)
    }
    await this.document.system.roll(rollType, item)
  }

  async _onDrop(event) {
    if (!this.isEditable || !this.isEditMode) return
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)

    // Handle different data types
    switch (data.type) {
      case "Item":
        const item = await fromUuid(data.uuid)
        return super._onDropItem(item)
    }
  }

}
