/**
 * 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;
  tagIds?: number[];
}

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, tagIds = [] } = 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 normalizedTagIds = [...tagIds].sort((a, b) => a - b);
  const tagIdsDependency = normalizedTagIds.join(',');

  const loadRecipes = async (currentOffset: number, append: boolean = false) => {
    setLoading(true);
    setError(null);
    try {
      const data = await fetchRecipes({
        search: search || undefined,
        offset: currentOffset,
        limit,
        tagIds: normalizedTagIds.length > 0 ? normalizedTagIds : undefined,
      });
      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, tagIdsDependency]);

  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,
  };
}
