import { YggdrasillUtility } from "./yggdrasill-utility.js";
import { YGGDRASILL_CONFIG } from "./yggdrasill-config.js";

const { HandlebarsApplicationMixin } = foundry.applications.api;

/**
 * Extend the basic ItemSheet with some very simple modifications
 * @extends {ItemSheetV2}
 */
export class YggdrasillItemSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ItemSheetV2) {
  constructor(options = {}) {
    super(options);
    this.#dragDrop = this.#createDragDropHandlers();
  }

  #dragDrop;

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-yggdrasill", "item"],
    position: {
      width: 550,
      height: 550,
    },
    form: {
      submitOnChange: true,
    },
    window: {
      resizable: true,
    },
    actions: {
      editImage: YggdrasillItemSheet.#onEditImage,
    },
  };

  /**
   * Tab groups state
   * @type {object}
   */
  tabGroups = { primary: "description" };

  /** @override */
  static PARTS = {
    sheet: {
      template: "systems/fvtt-yggdrasill/templates/item-{type}-sheet.hbs"
    }
  };

  /** @override */
  async _prepareContext() {
    // Ensure config is always available with fallback to direct import
    const config = game.system?.config || game.system?.yggdrasill?.config || YGGDRASILL_CONFIG || {};
    
    // Create options for niveau 0-5
    const optionsNiveaux4 = {};
    for (let i = 0; i <= 5; i++) {
      optionsNiveaux4[`${i}`] = `${i}`;
    }
    
    const optionsBase = YggdrasillUtility.createDirectOptionList(0, 20) || {};
    
    const context = {
      fields: this.document.schema.fields,
      systemFields: this.document.system.schema.fields,
      item: this.document,
      system: this.document.system,
      data: this.document.system,
      source: this.document.toObject(),
      enrichedDescription: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.description || "", { async: true }),
      enrichedEffet: await foundry.applications.ux.TextEditor.implementation.enrichHTML(this.document.system.effet || "", { async: true }),
      isEditMode: true,
      isEditable: this.isEditable,
      editable: this.isEditable,
      isGM: game.user.isGM,
      config: config,
      optionsBase: optionsBase,
      optionsNiveaux4: optionsNiveaux4,
    };
    return context;
  }
    return context;
  }

  /** @override */
  _onRender(context, options) {
    super._onRender(context, options);
    this.#dragDrop.forEach((d) => d.bind(this.element));
  }

  // #region Drag-and-Drop Workflow
  /**
   * Create drag-and-drop workflow handlers for this Application
   */
  #createDragDropHandlers() {
    return [];
  }

  // #region Actions

  /**
   * Handle editing the item image
   * @param {Event} event - The triggering event
   */
  static async #onEditImage(event) {
    event.preventDefault();
    const filePicker = new FilePicker({
      type: "image",
      current: this.document.img,
      callback: (path) => {
        this.document.update({ img: path });
      },
    });
    filePicker.browse();
  }
}
