import MGNEActorSheet from "./base-actor-sheet.mjs"
import { stripHtml } from "./character-sheet.mjs"

export default class MGNECreatureSheet extends MGNEActorSheet {
  static DEFAULT_OPTIONS = {
    classes: ["creature"],
    position: {
      width: 760,
      height: 680,
    },
    actions: {
      rollActionTable: MGNECreatureSheet.prototype._rollActionTable,
      clearActionTable: MGNECreatureSheet.prototype._clearActionTable,
      openActionTable: MGNECreatureSheet.prototype._openActionTable,
    },
  }

  static PARTS = {
    main: { template: "systems/fvtt-machine-gods-noxian-expanse/templates/creature-main.hbs" },
  }

  _processSubmitData(event, form, submitData) {
    // Foundry sends null for unchecked checkboxes in a SetField array — strip them
    if (Array.isArray(submitData.system?.creatureType)) {
      submitData.system.creatureType = submitData.system.creatureType.filter(v => v != null && v !== "")
    }
    return super._processSubmitData(event, form, submitData)
  }

  async _prepareContext() {
    const context = await super._prepareContext()
    context.traits = (this.document.itemTypes["creature-trait"] ?? [])
      .map(i => ({ id: i.id, name: i.name, img: i.img, system: i.system, tooltip: stripHtml(i.system.description) }))

    // Resolve linked action table
    const uuid = this.document.system.actionTableUuid
    if (uuid) {
      const table = await fromUuid(uuid).catch(() => null)
      context.actionTable = table ? { name: table.name, uuid } : null
    } else {
      context.actionTable = null
    }

    // Build creature type checkboxes
    const typeSet = this.document.system.creatureType ?? new Set()
    context.creatureTypes = ["human", "construct", "animal"].map(key => ({
      key,
      label: game.i18n.localize(`MGNE.Creature.Types.${key.charAt(0).toUpperCase() + key.slice(1)}`),
      checked: typeSet.has(key),
    }))

    return context
  }

  async _onDrop(event) {
    const data = foundry.applications.ux.TextEditor.implementation.getDragEventData(event)
    if (data?.type === "RollTable") {
      const table = await fromUuid(data.uuid)
      if (table) {
        await this.document.update({ "system.actionTableUuid": data.uuid })
        return
      }
    }
    return super._onDrop(event)
  }

  async _rollActionTable() {
    const uuid = this.document.system.actionTableUuid
    if (!uuid) return ui.notifications.warn(game.i18n.localize("MGNE.Creature.NoTableLinked"))
    const table = await fromUuid(uuid).catch(() => null)
    if (!table) return ui.notifications.warn(game.i18n.localize("MGNE.Creature.TableNotFound"))
    await table.draw()
  }

  async _clearActionTable() {
    await this.document.update({ "system.actionTableUuid": "" })
  }

  async _openActionTable() {
    const uuid = this.document.system.actionTableUuid
    if (!uuid) return
    const table = await fromUuid(uuid).catch(() => null)
    if (table) table.sheet.render(true)
  }
}
