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

export default class OathHammerArmySheet extends OathHammerActorSheet {
  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["army"],
    position: { width: 680, height: 560 },
    window: { contentClasses: ["army-content"] },
    actions: {
      openRegiment:   OathHammerArmySheet.#onOpenRegiment,
      removeRegiment: OathHammerArmySheet.#onRemoveRegiment,
      openLeader:     OathHammerArmySheet.#onOpenLeader,
      clearLeader:    OathHammerArmySheet.#onClearLeader,
    },
  }

  /** @override */
  static PARTS = {
    main:     { template: "systems/fvtt-oath-hammer/templates/actor/army-sheet.hbs" },
    tabs:     { template: "templates/generic/tab-navigation.hbs" },
    overview: { template: "systems/fvtt-oath-hammer/templates/actor/army-overview.hbs" },
    notes:    { template: "systems/fvtt-oath-hammer/templates/actor/army-notes.hbs" },
  }

  tabGroups = { sheet: "overview" }

  #getTabs() {
    const tabs = {
      overview: { id: "overview", group: "sheet", icon: "fa-solid fa-shield-halved", label: "OATHHAMMER.Tab.Overview" },
      notes:    { id: "notes",    group: "sheet", icon: "fa-solid fa-book",           label: "OATHHAMMER.Tab.Notes" },
    }
    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()
    const doc     = this.document
    context.tabs  = this.#getTabs()

    // Resolve leader
    const leaderUuid = doc.system.leaderUuid
    if (leaderUuid) {
      const leader = await fromUuid(leaderUuid)
      context.leader = leader ? { uuid: leaderUuid, name: leader.name, img: leader.img } : null
    } else {
      context.leader = null
    }

    return context
  }

  /** @override */
  async _preparePartContext(partId, context) {
    context = await super._preparePartContext(partId, context)
    const doc = this.document

    switch (partId) {
      case "overview": {
        context.tab = context.tabs.overview
        const refs = doc.system.regimentRefs ?? []
        const regiments = []
        let totalSupply = 0
        for (const id of refs) {
          const regiment = game.actors?.get(id)
          if (!regiment) continue
          totalSupply += regiment.system.supplyCost ?? 0
          regiments.push({
            id:         regiment.id,
            name:       regiment.name,
            img:        regiment.img,
            grit:       regiment.system.grit?.value ?? 0,
            gritMax:    regiment.system.grit?.max ?? 0,
            armor:      regiment.system.armorDice?.value ?? 0,
            movement:   regiment.system.movement ?? 0,
            supplyCost: regiment.system.supplyCost ?? 0,
          })
        }
        context.regiments   = regiments
        context.totalSupply = totalSupply
        break
      }

      case "notes":
        context.tab = context.tabs.notes
        context.enrichedNotes = await foundry.applications.ux.TextEditor.implementation.enrichHTML(
          doc.system.notes ?? "", { async: true }
        )
        break
    }
    return context
  }

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

    if (data.type === "Actor") {
      const actor = await fromUuid(data.uuid)
      if (!actor) return

      // Leader drop (on leader drop zone)
      if (event.target.closest(".army-leader-row")) {
        if (!actor.prototypeToken?.actorLink) {
          ui.notifications.warn(game.i18n.localize("OATHHAMMER.Warning.LeaderNotLinked"))
          return
        }
        return this.document.update({ "system.leaderUuid": actor.uuid })
      }

      // Regiment drop
      if (actor.type !== "regiment") return
      if (!actor.prototypeToken?.actorLink) {
        ui.notifications.warn(game.i18n.localize("OATHHAMMER.Warning.RegimentNotLinked"))
        return
      }
      const refs = foundry.utils.deepClone(this.document.system.regimentRefs ?? [])
      if (refs.includes(actor.id)) return
      refs.push(actor.id)
      return this.document.update({ "system.regimentRefs": refs })
    }
  }

  // ── Actions ─────────────────────────────────────────────────────────────────

  static async #onOpenRegiment(event, target) {
    const actor = game.actors?.get(target.dataset.actorId)
    if (actor) actor.sheet.render(true)
  }

  static async #onRemoveRegiment(event, target) {
    const id   = target.dataset.actorId
    const refs = (this.document.system.regimentRefs ?? []).filter(r => r !== id)
    await this.document.update({ "system.regimentRefs": refs })
  }

  static async #onOpenLeader() {
    const uuid = this.document.system.leaderUuid
    if (!uuid) return
    const leader = await fromUuid(uuid)
    if (leader) leader.sheet.render(true)
  }

  static async #onClearLeader() {
    await this.document.update({ "system.leaderUuid": null })
  }
}
