/**
 * Application to configure weapon types and groups
 */
import { getWeaponTypes, getWeaponGroups } from "../config/weapon.mjs"

export class WeaponTypesConfig extends FormApplication {

  constructor(object, options) {
    super(object, options)

    // Store working copies that won't trigger settings changes
    this.workingTypes = null
    this.workingGroups = null
  }

  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      title: game.i18n.localize("PRISMRPG.Settings.weaponTypesConfig.title"),
      id: "weapon-types-config",
      classes: ["prismrpg", "weapon-types-config"],
      template: "systems/fvtt-prism-rpg/templates/weapon-types-config.hbs",
      width: 1000,
      height: "auto",
      closeOnSubmit: true,
      submitOnChange: false,
      tabs: [{ navSelector: ".tabs", contentSelector: ".content", initial: "types" }]
    })
  }

  getData() {
    const data = super.getData()

    // Get default weapon types from config with proper translation keys
    const defaultTypes = getWeaponTypes()

    // Get default weapon groups from config with proper translation keys
    const defaultGroups = getWeaponGroups()

    // Initialize working copies on first render
    if (!this.workingTypes) {
      const customTypes = game.settings.get("fvtt-prism-rpg", "customWeaponTypes") || {}
      this.workingTypes = foundry.utils.deepClone(customTypes)
    }

    if (!this.workingGroups) {
      const customGroups = game.settings.get("fvtt-prism-rpg", "customWeaponGroups") || {}
      this.workingGroups = foundry.utils.deepClone(customGroups)
    }

    // Merge default and working copies
    data.weaponTypes = {}
    const mergedTypes = foundry.utils.mergeObject(defaultTypes, this.workingTypes, { inplace: false })
    console.log("Merged types in getData:", mergedTypes)
    for (const [key, type] of Object.entries(mergedTypes)) {
      data.weaponTypes[key] = {
        ...type,
        // Translate label if it's a translation key
        label: type.label.startsWith("PRISMRPG.") ? game.i18n.localize(type.label) : type.label,
        // Mark if it's a custom type (can be deleted)
        isCustom: key.startsWith("custom_")
      }
    }

    data.weaponGroups = {}
    const mergedGroups = foundry.utils.mergeObject(defaultGroups, this.workingGroups, { inplace: false })
    for (const [key, group] of Object.entries(mergedGroups)) {
      data.weaponGroups[key] = {
        ...group,
        // Translate labels if they're translation keys
        label: group.label.startsWith("PRISMRPG.") ? game.i18n.localize(group.label) : group.label,
        passiveLabel: group.passiveLabel.startsWith("PRISMRPG.") ? game.i18n.localize(group.passiveLabel) : group.passiveLabel,
        passiveDescription: group.passiveDescription.startsWith("PRISMRPG.") ? game.i18n.localize(group.passiveDescription) : group.passiveDescription,
        // Mark if it's a custom group (can be deleted)
        isCustom: key.startsWith("custom_")
      }
    }

    return data
  }

  activateListeners(html) {
    super.activateListeners(html)

    // Add new weapon type
    html.find('[data-action="add-weapon-type"]').click(this._onAddWeaponType.bind(this))

    // Delete weapon type
    html.find('[data-action="delete-weapon-type"]').click(this._onDeleteWeaponType.bind(this))

    // Add new weapon group
    html.find('[data-action="add-weapon-group"]').click(this._onAddWeaponGroup.bind(this))

    // Delete weapon group
    html.find('[data-action="delete-weapon-group"]').click(this._onDeleteWeaponGroup.bind(this))

    // Reset to defaults
    html.find('[data-action="reset-defaults"]').click(this._onResetDefaults.bind(this))

    console.log("Listeners activated, weapon types count:", html.find('.weapon-type-entry').length)
  }

  async _onAddWeaponType(event) {
    event.preventDefault()

    const newId = `custom_${foundry.utils.randomID()}`

    // Add new empty type to working copy (no settings save)
    this.workingTypes[newId] = {
      id: newId,
      label: "New Weapon Type",
      apc: 1,
      hands: 1
    }

    // Force re-render without saving
    this.render(true)
  }

  async _onDeleteWeaponType(event) {
    event.preventDefault()
    const typeId = $(event.currentTarget).data('id')

    console.log("Delete weapon type clicked:", typeId)
    console.log("Working types before:", this.workingTypes)

    // Delete from working copy (no settings save)
    delete this.workingTypes[typeId]

    console.log("Working types after:", this.workingTypes)

    // Save to settings immediately so it persists
    await game.settings.set("fvtt-prism-rpg", "customWeaponTypes", this.workingTypes)

    // Find and remove the entry from DOM immediately
    this.element.find(`.weapon-type-entry[data-id="${typeId}"]`).remove()
  }

  async _onAddWeaponGroup(event) {
    event.preventDefault()

    const newId = `custom_${foundry.utils.randomID()}`

    // Add new empty group to working copy (no settings save)
    this.workingGroups[newId] = {
      id: newId,
      label: "New Weapon Group",
      passive: "newPassive",
      passiveLabel: "New Passive",
      passiveDescription: "Description of the new passive ability."
    }

    // Force re-render without saving
    this.render(true)
  }

  async _onDeleteWeaponGroup(event) {
    event.preventDefault()
    const groupId = $(event.currentTarget).data('id')

    // Delete from working copy (no settings save)
    delete this.workingGroups[groupId]

    // Save to settings immediately so it persists
    await game.settings.set("fvtt-prism-rpg", "customWeaponGroups", this.workingGroups)

    // Find and remove the entry from DOM immediately
    this.element.find(`.weapon-group-entry[data-id="${groupId}"]`).remove()
  }

  async _onResetDefaults(event) {
    event.preventDefault()

    const confirm = await Dialog.confirm({
      title: game.i18n.localize("PRISMRPG.Settings.resetConfirm.title"),
      content: game.i18n.localize("PRISMRPG.Settings.resetConfirm.content"),
      yes: () => true,
      no: () => false
    })

    if (confirm) {
      // Reset working copies
      this.workingTypes = {}
      this.workingGroups = {}
      this.render(true)
    }
  }

  async _updateObject(event, formData) {
    const expanded = foundry.utils.expandObject(formData)

    // Extract only custom types (those with custom_ prefix)
    const customTypes = {}
    if (expanded.weaponTypes) {
      for (const [key, type] of Object.entries(expanded.weaponTypes)) {
        if (key.startsWith("custom_")) {
          customTypes[key] = type
        }
      }
    }

    // Extract only custom groups (those with custom_ prefix)
    const customGroups = {}
    if (expanded.weaponGroups) {
      for (const [key, group] of Object.entries(expanded.weaponGroups)) {
        if (key.startsWith("custom_")) {
          customGroups[key] = group
        }
      }
    }

    // Save custom weapon types (this will trigger page reload)
    await game.settings.set("fvtt-prism-rpg", "customWeaponTypes", customTypes)

    // Save custom weapon groups (this will trigger page reload)
    await game.settings.set("fvtt-prism-rpg", "customWeaponGroups", customGroups)

    ui.notifications.info(game.i18n.localize("PRISMRPG.Settings.weaponTypesSaved"))
  }
}
