import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import * as managementApi from "@/api/recipe-management.api";
import { extractApiError } from "@/api/axiosInstance";
import type { CreateRecipeInput } from "@/types/recipe-management.types";

export function useRecipeManagement() {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  const invalidateRecipes = () => queryClient.invalidateQueries({ queryKey: ["recipes"] });

  const createMutation = useMutation({
    mutationFn: (input: CreateRecipeInput) => managementApi.createRecipe(input),
    onSuccess: invalidateRecipes,
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, input }: { id: number; input: CreateRecipeInput }) =>
      managementApi.updateRecipe(id, input),
    onSuccess: invalidateRecipes,
  });

  const importMutation = useMutation({
    mutationFn: (file: File) => managementApi.importRecipesFromExcel(file),
    onSuccess: invalidateRecipes,
  });

  const recalculateMutation = useMutation({
    mutationFn: () => managementApi.recalculateAllRecipeMacros(),
    onSuccess: invalidateRecipes,
  });

  return {
    createRecipe: createMutation.mutateAsync,
    createPending: createMutation.isPending,
    createError: createMutation.isError
      ? extractApiError(createMutation.error, t("errors.saveRecipeFailed"))
      : null,
    resetCreateError: createMutation.reset,
    updateRecipe: updateMutation.mutateAsync,
    updatePending: updateMutation.isPending,
    updateError: updateMutation.isError
      ? extractApiError(updateMutation.error, t("errors.saveRecipeFailed"))
      : null,
    resetUpdateError: updateMutation.reset,
    importExcel: importMutation.mutateAsync,
    importPending: importMutation.isPending,
    importError: importMutation.isError
      ? extractApiError(importMutation.error, t("errors.importFailed"))
      : null,
    importResult: importMutation.data ?? null,
    resetImport: importMutation.reset,
    downloadTemplate: managementApi.downloadImportTemplate,
    recalculateMacros: recalculateMutation.mutateAsync,
    recalculatePending: recalculateMutation.isPending,
    recalculateError: recalculateMutation.isError
      ? extractApiError(recalculateMutation.error, t("errors.recalculateMacrosFailed"))
      : null,
    resetRecalculateError: recalculateMutation.reset,
  };
}
