/**
 * Hook for fetching and managing recipes
 */

import { useState, useEffect } from 'react';
import { fetchRecipes } from '../services/api';
import type { Recipe } from '../types/recipe';

interface UseRecipesOptions {
  search?: string;
  limit?: number;
  tagId?: number | null;
}

interface UseRecipesResult {
  recipes: Recipe[];
  loading: boolean;
  error: string | null;
  hasMore: boolean;
  loadMore: () => void;
  refresh: () => void;
}

export function useRecipes(options: UseRecipesOptions = {}): UseRecipesResult {
  const { search = '', limit = 20, tagId = null } = options;
  const [recipes, setRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState(true);

  const loadRecipes = async (currentOffset: number, append: boolean = false) => {
    setLoading(true);
    setError(null);
    try {
      const data = await fetchRecipes({
        search: search || undefined,
        offset: currentOffset,
        limit,
        tagId,
      });
      if (append) {
        setRecipes(prev => [...prev, ...data]);
      } else {
        setRecipes(data);
      }
      setHasMore(data.length === limit);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load recipes');
      setRecipes([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setOffset(0);
    setHasMore(true);
    loadRecipes(0, false);
  }, [search, tagId]);

  const loadMore = () => {
    if (!loading && hasMore) {
      const newOffset = offset + limit;
      setOffset(newOffset);
      loadRecipes(newOffset, true);
    }
  };

  const refresh = () => {
    setOffset(0);
    setHasMore(true);
    loadRecipes(0, false);
  };

  return {
    recipes,
    loading,
    error,
    hasMore,
    loadMore,
    refresh,
  };
}
