import { useState, useCallback } from 'react';
import type { RecipeSummaryDTO, CreateRecipeRequest, RecipeStatus } from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface RecipesState {
  recipes: RecipeSummaryDTO[];
  loading: boolean;
  error: string | null;
}

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function useRecipes() {
  const [state, setState] = useState<RecipesState>({
    recipes: [],
    loading: false,
    error: null,
  });

  const fetchRecipes = useCallback(async (status?: RecipeStatus) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const recipes = await client.recipes.list(status);
      setState({ recipes, loading: false, error: null });
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
    }
  }, []);

  const createRecipe = useCallback(async (request: CreateRecipeRequest) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const recipe = await client.recipes.create(request);
      const recipes = await client.recipes.list();
      setState({ recipes, loading: false, error: null });
      return recipe;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const clearError = useCallback(() => {
    setState((s) => ({ ...s, error: null }));
  }, []);

  return {
    ...state,
    fetchRecipes,
    createRecipe,
    clearError,
  };
}
