import { TEMPLATE_DESCRIPTION } from "../../common/_module.mjs";
import { ITEM_TYPES } from "../../constants.js";
import { Misc } from "../../misc.js";
import { RdDTextEditor } from "../../apps/rdd-text-roll-editor.js";
import RdDItemBaseSheet from "./common-item-sheet.mjs";

export default class RdDRecetteAlchimiqueSheet extends RdDItemBaseSheet {
  static get ITEM_TYPE() { return ITEM_TYPES.recettealchimique; }
  static get TEMPLATES() { return [TEMPLATE_DESCRIPTION]; }

  static RESULTAT_TYPES = {
    potion: 'Potion',
    objet: 'Objet',
    gemme: 'Gemme',
    nourritureboisson: 'Nourriture/Boisson',
    ingredient: 'Ingrédient',
    herbe: 'Herbe',
    plante: 'Plante',
    faune: 'Faune',
    armure: 'Armure',
    arme: 'Arme',
    munition: 'Munition',
  }

  static DEFAULT_OPTIONS = Object.assign({},
    RdDItemBaseSheet.DEFAULT_OPTIONS,
    {
      classes: ["fvtt-rdd", "item", "recettealchimique"],
      position: { width: 600 },
      window: { contentClasses: ["recettealchimique-content"] },
      actions: {
        addIngredient: RdDRecetteAlchimiqueSheet.#onAddIngredient,
        deleteIngredient: RdDRecetteAlchimiqueSheet.#onDeleteIngredient,
        extractIngredients: RdDRecetteAlchimiqueSheet.#onExtractIngredients,
      },
    });

  static PARTS = {
    main: {
      template: "systems/foundryvtt-reve-de-dragon/templates/sheets/item/recettealchimique.hbs",
    },
  };

  async _prepareContext() {
    const item = this.document;
    const enriched = {
      manipulation: await RdDTextEditor.enrichHTML(item.system.manipulation, item),
      utilisation: await RdDTextEditor.enrichHTML(item.system.utilisation, item),
      enchantement: await RdDTextEditor.enrichHTML(item.system.enchantement, item),
      sureffet: await RdDTextEditor.enrichHTML(item.system.sureffet, item),
    };
    return Object.assign(
      await super._prepareContext(),
      {
        enriched,
        parsedIngredients: Misc.safeJsonParse(item.system.ingredients, []),
        parsedResultat: Misc.safeJsonParse(item.system.resultat, { type: 'objet', name: '', quantite: 1 }),
        resultatTypes: RdDRecetteAlchimiqueSheet.RESULTAT_TYPES,
        INGREDIENT_TYPES: RdDRecetteAlchimiqueSheet.INGREDIENT_TYPES,
        INGREDIENT_UNITS: RdDRecetteAlchimiqueSheet.INGREDIENT_UNITS,
      }
    );
  }

  _onChangeForm(event, formData) {
    const obj = formData?.object;
    if (!obj) return super._onChangeForm(event, formData);

    const target = event.target;
    if (target?.name?.startsWith('ingredient-')) {
      const ingredients = [];
      const rows = this.element?.querySelectorAll('.ingredient-row') ?? [];
      rows.forEach(row => {
        const i = row.dataset.index;
        if (i === undefined) return;
        ingredients.push({
          nom: row.querySelector(`[name="ingredient-nom-${i}"]`)?.value ?? '',
          type: row.querySelector(`[name="ingredient-type-${i}"]`)?.value ?? 'herbe',
          quantite: parseInt(row.querySelector(`[name="ingredient-quantite-${i}"]`)?.value) || 1,
          unite: row.querySelector(`[name="ingredient-unite-${i}"]`)?.value ?? 'brin',
          consommable: row.querySelector(`[name="ingredient-consommable-${i}"]`)?.checked ?? true,
        });
      });
      obj['system.ingredients'] = JSON.stringify(ingredients);
    }

    const rType = obj['system.resultat-type'];
    const rName = obj['system.resultat-name'];
    const rQty = obj['system.resultat-quantite'];
    if (rType !== undefined || rName !== undefined || rQty !== undefined) {
      const cur = Misc.safeJsonParse(this.document.system.resultat, {});
      if (rType !== undefined) cur.type = rType;
      if (rName !== undefined) cur.name = rName;
      if (rQty !== undefined) cur.quantite = parseInt(rQty) || 1;
      obj['system.resultat'] = JSON.stringify(cur);
      delete obj['system.resultat-type'];
      delete obj['system.resultat-name'];
      delete obj['system.resultat-quantite'];
    }
    return super._onChangeForm(event, formData);
  }

  static INGREDIENT_TYPES = {
    herbe: 'Herbe',
    ingredient: 'Ingrédient',
    plante: 'Plante',
    objet: 'Objet',
    autre: 'Autre',
  }

  static INGREDIENT_UNITS = {
    brin: 'brin',
    pépin: 'pépin',
    écaille: 'écaille',
    mesure: 'mesure',
    doigt: 'doigt',
    déhacoudre: 'déhacoudre',
    livre: 'livre',
    poignée: 'poignée',
    unité: 'unité',
  }

  static async #onAddIngredient(event, target) {
    const ingredients = Misc.safeJsonParse(this.document.system.ingredients, []);
    ingredients.push({ nom: '', type: 'herbe', quantite: 1, unite: 'brin', consommable: true });
    await this.document.update({ 'system.ingredients': JSON.stringify(ingredients) });
  }

  static async #onDeleteIngredient(event, target) {
    const index = parseInt(target.dataset.index);
    if (isNaN(index)) return;
    const ingredients = Misc.safeJsonParse(this.document.system.ingredients, []);
    ingredients.splice(index, 1);
    await this.document.update({ 'system.ingredients': JSON.stringify(ingredients) });
  }

  static async #onExtractIngredients(event, target) {
    ui.notifications.warn('L\'extraction automatique des ingrédients n\'est pas encore implémentée.');
  }
}
