import LesOubliesActorSheet from "./base-actor-sheet.mjs"
import { LesOubliesUtility } from "../../les-oublies-utility.js"

export default class LesOubliesCompagnieSheet extends LesOubliesActorSheet {
  static DEFAULT_OPTIONS = {
    ...super.DEFAULT_OPTIONS,
    classes: [...super.DEFAULT_OPTIONS.classes, "compagnie"],
    actions: {
      ...super.DEFAULT_OPTIONS.actions,
      switchTab: LesOubliesCompagnieSheet.#onSwitchTab,
    },
    window: {
      ...super.DEFAULT_OPTIONS.window,
      title: "TYPES.Actor.compagnie",
    },
  }

  static PARTS = {
    sheet: {
      template: "systems/fvtt-les-oublies/templates/actor-compagnie-sheet-v5.hbs",
    },
  }

  _activeTab = "power"

  #getTabs() {
    const tabs = {
      power: { id: "power", label: "Pouvoir", icon: "fa-solid fa-burst" },
      members: { id: "members", label: "Membres & liens", icon: "fa-solid fa-people-group" },
      notes: { id: "notes", label: "Notes", icon: "fa-solid fa-feather-pointed" },
    }

    for (const tab of Object.values(tabs)) {
      tab.active = this._activeTab === tab.id
      tab.cssClass = tab.active ? "active" : ""
    }

    return tabs
  }

  async _prepareContext() {
    const context = await super._prepareContext()
    context.tabs = this.#getTabs()
    context.members = (this.document.system.memberIds ?? []).map((id) => game.actors.get(id)).filter(Boolean)
    context.captain = this.document.system.captainId ? game.actors.get(this.document.system.captainId) : null
    context.shadow = this.document.system.ombreDuTourmentId ? game.actors.get(this.document.system.ombreDuTourmentId) : null
    context.powers = this.document.getEmbeddedItems("pouvoircompagnie")
    context.primaryPower = context.powers[0] ?? null
    context.links = (this.document.system.links ?? []).map((link) => ({
      ...link,
      sourceLabel: game.actors.get(link.sourceId)?.name ?? link.sourceId,
      targetLabel: game.actors.get(link.targetId)?.name ?? link.targetId,
    }))
    const actorChoices = LesOubliesUtility.sortByName(game.actors.filter((actor) => actor.type === "personnage")).map((actor) => ({
      value: actor.id,
      label: actor.name,
    }))
    context.choiceSets.captainOptions = LesOubliesUtility.ensureChoice(actorChoices, this.document.system.captainId, context.captain?.name)
    context.choiceSets.shadowOptions = LesOubliesUtility.ensureChoice(actorChoices, this.document.system.ombreDuTourmentId, context.shadow?.name)
    return context
  }

  static #onSwitchTab(event, target) {
    const tab = target.dataset.tab
    if (!tab || this._activeTab === tab) return
    this._activeTab = tab
    this.render()
  }
}
