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

/**
 * Hook for fetching and managing a single recipe
 */
export function useRecipe(id: number | null) {
  const [recipe, setRecipe] = useState<Recipe | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (id === null) {
      // New recipe mode - no fetch needed
      setRecipe(null);
      setLoading(false);
      return;
    }

    let mounted = true;

    async function loadRecipe() {
      if (id === null) return; // Type guard for TypeScript
      
      try {
        setLoading(true);
        setError(null);
        const data = await fetchRecipe(id);
        if (mounted) {
          setRecipe(data);
        }
      } catch (err) {
        if (mounted) {
          setError(err instanceof Error ? err.message : 'Failed to load recipe');
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
      }
    }

    loadRecipe();

    return () => {
      mounted = false;
    };
  }, [id]);

  return { recipe, loading, error, refetch: () => setRecipe(null) };
}
