import EcrymeBaseActorSheet from "./base-actor-sheet.js"
import { EcrymeUtility } from "../../common/ecryme-utility.js"

/**
 * Actor sheet for the Annency type using Application V2.
 */
export default class EcrymeAnnencySheet extends EcrymeBaseActorSheet {

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["annency"],
    position: { width: 640, height: 600 },
    actions: {
      actorEdit:   EcrymeAnnencySheet.#onActorEdit,
      actorDelete: EcrymeAnnencySheet.#onActorDelete,
      itemEdit:    EcrymeAnnencySheet.#onItemEdit,
      itemDelete:  EcrymeAnnencySheet.#onItemDelete,
      itemCreate:  EcrymeAnnencySheet.#onItemCreate,
    },
  }

  /** @override */
  static PARTS = {
    header:  { template: "systems/fvtt-ecryme/templates/actors/partials/actor-header.hbs" },
    tabs:    { template: "templates/generic/tab-navigation.hbs" },
    annency: { template: "systems/fvtt-ecryme/templates/actors/annency-annency.hbs" },
    boheme:  { template: "systems/fvtt-ecryme/templates/actors/annency-boheme.hbs" },
  }

  /** @override */
  tabGroups = { primary: "annency" }

  /** Build tabs conditionally based on active modules */
  _getTabs() {
    const tabs = {}
    if (EcrymeUtility.hasCephaly()) {
      tabs.annency = { id: "annency", group: "primary", label: "ECRY.ui.annency" }
    }
    if (EcrymeUtility.hasBoheme()) {
      tabs.boheme = { id: "boheme", group: "primary", label: "ECRY.ui.boheme" }
    }
    // Ensure initial tab is valid
    if (!tabs[this.tabGroups.primary]) {
      this.tabGroups.primary = Object.keys(tabs)[0] ?? "annency"
    }
    for (const tab of Object.values(tabs)) {
      tab.active = this.tabGroups[tab.group] === tab.id
      tab.cssClass = tab.active ? "active" : ""
    }
    return tabs
  }

  /** @override */
  async _prepareContext() {
    const actor = this.document
    return {
      actor,
      system:       actor.system,
      source:       actor.toObject(),
      fields:       actor.schema.fields,
      systemFields: actor.system.schema.fields,
      type:         actor.type,
      img:          actor.img,
      name:         actor.name,
      isEditable:   this.isEditable,
      config:       game.ecryme.config,
      hasCephaly:   EcrymeUtility.hasCephaly(),
      hasBoheme:    EcrymeUtility.hasBoheme(),
      characters:   actor.buildAnnencyActorList(),
      owner:        this.document.isOwner,
      isGM:         game.user.isGM,
      tabs:         this._getTabs(),
    }
  }

  /** @override */
  async _preparePartContext(partId, context) {
    context = await super._preparePartContext(partId, context)
    if (partId === "annency" || partId === "boheme") {
      context.tab = context.tabs[partId]
    }
    return context
  }

  /** @override */
  async _onDrop(event) {
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)
    if (data?.type === "Actor") {
      const actor = await fromUuid(data.uuid)
      if (actor) {
        this.actor.addAnnencyActor(actor.id)
      } else {
        ui.notifications.warn("Actor not found")
      }
    }
  }

  // #region Static Action Handlers

  static #onActorEdit(event, target) {
    const li = target.closest("[data-actor-id]")
    game.actors.get(li?.dataset.actorId)?.sheet.render(true)
  }

  static async #onActorDelete(event, target) {
    const li = target.closest("[data-actor-id]")
    this.actor.removeAnnencyActor(li?.dataset.actorId)
  }

  static #onItemEdit(event, target) {
    const li = target.closest("[data-item-id]")
    const itemId = li?.dataset.itemId ?? target.dataset.itemId
    this.document.items.get(itemId)?.sheet.render(true)
  }

  static async #onItemDelete(event, target) {
    const li = target.closest("[data-item-id]")
    EcrymeUtility.confirmDelete(this, $(li)).catch(() => {})
  }

  static async #onItemCreate(event, target) {
    const dataType = target.dataset.type
    await this.document.createEmbeddedDocuments("Item", [{ name: "NewItem", type: dataType }], { renderSheet: true })
  }

  // #endregion
}
