import { formatCredits } from './tradeHelper.js';
import { createNpcActor, generateClientMission, generateEncounter, generateQuickNpc } from './npcHelper.js';
import { NPC_RELATIONS } from './data/npcTables.js';

const MODULE_ID = 'mgt2-compendium-amiral-denisov';

export class NpcDialog extends FormApplication {
  constructor(options = {}) {
    super({}, options);
    this._formData = {
      npc: {
        relation: options.relation ?? 'contact',
        experienceBias: 'random',
        createActor: false,
        actorName: '',
        openCreatedActor: true,
      },
      encounter: {
        context: options.context ?? 'starport',
        includeFollowUp: true,
      },
    };
  }

  static get defaultOptions() {
    return foundry.utils.mergeObject(super.defaultOptions, {
      id: 'mgt2-npc',
      title: 'PNJ & Rencontres – MGT2',
      template: `modules/${MODULE_ID}/templates/npc-dialog.hbs`,
      width: 720,
      height: 'auto',
      resizable: true,
      tabs: [{
        navSelector: '.tabs',
        contentSelector: '.tab-content',
        initial: 'npc',
      }],
      classes: ['mgt2-npc-dialog'],
    });
  }

  getData() {
    registerHandlebarsHelpers();
    return foundry.utils.mergeObject(super.getData(), {
      ...this._formData,
      relations: Object.entries(NPC_RELATIONS).map(([key, value]) => ({ key, label: value.label })),
    });
  }

  activateListeners(html) {
    super.activateListeners(html);

    html.find('[data-action="generate-npc"]').on('click', async (event) => {
      event.preventDefault();
      this._readForm(html);
      await this._handleNpc();
    });

    html.find('[data-action="generate-encounter"]').on('click', async (event) => {
      event.preventDefault();
      this._readForm(html);
      await this._handleEncounter();
    });

    html.find('[data-action="generate-mission"]').on('click', async (event) => {
      event.preventDefault();
      await this._handleMission();
    });

    if (this.options.initialTab) {
      this._tabs?.[0]?.activate(this.options.initialTab);
    }
  }

  _readForm(html) {
    this._formData.npc.relation = html.find('[name="npc.relation"]').val();
    this._formData.npc.experienceBias = html.find('[name="npc.experienceBias"]').val();
    this._formData.npc.createActor = html.find('[name="npc.createActor"]').is(':checked');
    this._formData.npc.actorName = html.find('[name="npc.actorName"]').val();
    this._formData.npc.openCreatedActor = html.find('[name="npc.openCreatedActor"]').is(':checked');
    this._formData.encounter.context = html.find('[name="encounter.context"]').val();
    this._formData.encounter.includeFollowUp = html.find('[name="encounter.includeFollowUp"]').is(':checked');
  }

  async _handleNpc() {
    const result = await generateQuickNpc(this._formData.npc);
    if (this._formData.npc.createActor) {
      const actor = await createNpcActor(result, {
        name: this._formData.npc.actorName,
        openSheet: this._formData.npc.openCreatedActor,
      });
      result.createdActor = {
        id: actor.id,
        name: actor.name,
      };
      ui.notifications.info(`Fiche PNJ créée : ${actor.name}`);
    }
    await this._postToChatResult(result);
  }

  async _handleEncounter() {
    const result = await generateEncounter(this._formData.encounter);
    await this._postToChatResult(result);
  }

  async _handleMission() {
    const result = await generateClientMission();
    await this._postToChatResult(result);
  }

  async _postToChatResult(data) {
    registerHandlebarsHelpers();
    const renderHbs = foundry.applications?.handlebars?.renderTemplate ?? renderTemplate;
    const html = await renderHbs(`modules/${MODULE_ID}/templates/npc-result.hbs`, data);

    await ChatMessage.create({
      content: html,
      speaker: ChatMessage.getSpeaker(),
      flags: { [MODULE_ID]: { type: 'npc-result' } },
    });
  }

  async _updateObject(_event, _formData) {}
}

let helpersRegistered = false;

function registerHandlebarsHelpers() {
  if (helpersRegistered) return;
  helpersRegistered = true;

  Handlebars.registerHelper('eq', (a, b) => a === b);
  Handlebars.registerHelper('join', (arr, sep) => (Array.isArray(arr) ? arr.join(sep) : ''));
  Handlebars.registerHelper('formatCredits', (amount) => formatCredits(amount));
  Handlebars.registerHelper('contains', (text, search) => String(text ?? '').includes(search));
}
