import { RecipeEditor } from "/static/js/modules/recipes/recipe-editor.js";
import { SyncPanel } from "/static/js/modules/recipes/sync-panel.js";
import { DispenserSelector } from "/static/js/modules/recipes/dispenser-selector.js";
import { initRecipeMobileSheetGestures } from "/static/js/modules/recipes/recipe-mobile-sheet-gestures.js";

let initialized = false;

export function initRecipesPage(handlers) {
  if (initialized) return;
  initialized = true;

  const recipeEditorModule = new RecipeEditor({
    addIngredient: handlers.addIngredient,
    toggleUnloadingLink: handlers.toggleUnloadingLink,
    addUnloadingGroup: handlers.addUnloadingGroup,
    showRecipeEdit: handlers.showRecipeEdit,
    printAllRecipesInPeriod: handlers.printAllRecipesInPeriod,
    printRecipe: handlers.printRecipe,
    saveRecipe: handlers.saveRecipe,
    moveGroupUp: handlers.moveGroupUp,
    moveGroupDown: handlers.moveGroupDown,
    removeUnloadingGroup: handlers.removeUnloadingGroup,
    moveIngredientUp: handlers.moveIngredientUp,
    moveIngredientDown: handlers.moveIngredientDown,
    removeIngredient: handlers.removeIngredient,
    openIngredientMobileSheet: handlers.openIngredientMobileSheet,
    closeIngredientMobileSheet: handlers.closeIngredientMobileSheet,
    removeIngredientFromSheet: handlers.removeIngredientFromSheet,
    openUnloadingGroupMobileSheet: handlers.openUnloadingGroupMobileSheet,
    closeUnloadingGroupMobileSheet: handlers.closeUnloadingGroupMobileSheet,
    handleGroupTypeChange: handlers.handleGroupTypeChange,
    validateGroupValue: handlers.validateGroupValue,
    handleIngredientChange: handlers.handleIngredientChange,
    handleDryMatterPercentChange: handlers.handleDryMatterPercentChange,
    recalculateWeights: handlers.recalculateWeights,
    recalculateFromTotalWeight: handlers.recalculateFromTotalWeight,
  });

  const syncPanelModule = new SyncPanel({
    openSettings: handlers.openSettings,
    closeSettings: handlers.closeSettings,
    toggleCredentialsForm: handlers.toggleCredentialsForm,
    toggleSyncForm: handlers.toggleSyncForm,
    changeCredentials: handlers.changeCredentials,
    editSyncClientSettings: handlers.editSyncClientSettings,
    deleteSyncClientSettings: handlers.deleteSyncClientSettings,
    saveSyncClientDisplayName: handlers.saveSyncClientDisplayName,
    loadSyncClientsSettings: handlers.loadSyncClientsSettings,
  });

  const dispenserSelectorModule = new DispenserSelector({
    selectDispenser: handlers.selectDispenser,
    selectRecipe: handlers.selectRecipe,
    selectPeriod: handlers.selectPeriod,
    copyRecipe: handlers.copyRecipe,
    deleteRecipe: handlers.deleteRecipe,
    unskipRecipeToday: handlers.unskipRecipeToday,
    unskipIngredientPartsToday: handlers.unskipIngredientPartsToday,
    unskipGroupPartsToday: handlers.unskipGroupPartsToday,
    pasteRecipe: handlers.pasteRecipe,
    createNewRecipe: handlers.createNewRecipe,
    moveRecipeUp: handlers.moveRecipeUp,
    moveRecipeDown: handlers.moveRecipeDown,
  });

  initRecipeMobileSheetGestures({
    closeIngredientMobileSheet: handlers.closeIngredientMobileSheet,
    closeUnloadingGroupMobileSheet: handlers.closeUnloadingGroupMobileSheet,
    closeRecipeHelpModal: handlers.closeRecipeHelpModal,
  });

  const createRecipeBtn = document.getElementById("createRecipeBtn");
  if (createRecipeBtn) {
    createRecipeBtn.addEventListener("click", (event) => {
      event.stopPropagation();
      const selectedDispenser = handlers.getSelectedDispenser();
      if (selectedDispenser) {
        handlers.createNewRecipeForMill(selectedDispenser);
      }
    });
  }

  document.addEventListener("click", async (event) => {
    const actionEl = event.target.closest("[data-action]");
    if (!actionEl) return;

    const action = actionEl.dataset.action;
    if (await syncPanelModule.handleAction(action, event, actionEl)) return;
    if (await dispenserSelectorModule.handleAction(action, event, actionEl)) return;
    if (await recipeEditorModule.handleAction(action, event, actionEl)) return;

    if (action === "open-recipe-help") {
      event.preventDefault();
      handlers.openRecipeHelp?.(actionEl.id);
      return;
    }

    if (action === "close-recipe-help") {
      event.preventDefault();
      handlers.closeRecipeHelpModal?.();
      return;
    }

    if (action === "mobile-dashboard-back") {
      event.preventDefault();
      handlers.mobileDashboardBack?.();
      return;
    }

    if (action === "logout") {
      event.preventDefault();
      handlers.logout();
    }
  });

  document.addEventListener("change", (event) => {
    const actionEl = event.target.closest("[data-action]");
    if (!actionEl) return;
    const action = actionEl.dataset.action;
    recipeEditorModule.handleChange(action, actionEl);
  });

  document.addEventListener("keydown", (event) => {
    if (event.key !== "Escape") return;
    const ingSheet = document.getElementById("ingredientMobileSheet");
    if (ingSheet && !ingSheet.hidden) {
      handlers.closeIngredientMobileSheet?.();
      return;
    }
    const grpSheet = document.getElementById("unloadingGroupMobileSheet");
    if (grpSheet && !grpSheet.hidden) {
      handlers.closeUnloadingGroupMobileSheet?.();
    }
  });
}
