import React, { useEffect, useState } from 'react';
import RecipeService, { Recipe } from '../services/RecipeService';

const RecipeList: React.FC = () => {
  const [recipes, setRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchRecipes = async () => {
      try {
        const data = await RecipeService.getRecipes();
        setRecipes(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Une erreur est survenue');
      } finally {
        setLoading(false);
      }
    };

    fetchRecipes();
  }, []);

  const handleDelete = async (id: string) => {
    if (window.confirm('Êtes-vous sûr de vouloir supprimer cette recette?')) {
      try {
        await RecipeService.deleteRecipe(id);
        setRecipes(recipes.filter(recipe => recipe.id !== id));
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Erreur lors de la suppression');
      }
    }
  };

  if (loading) return <div>Chargement des recettes...</div>;
  if (error) return <div className="error-message">{error}</div>;

  return (
    <div className="recipe-list">
      <h2>Mes recettes</h2>

      {recipes.length === 0 ? (
        <p>Vous n'avez pas encore de recettes. Créez-en une!</p>
      ) : (
        <ul>
          {recipes.map(recipe => (
            <li key={recipe.id} className="recipe-item">
              <h3>{recipe.title}</h3>
              <p><strong>Ingrédients:</strong> {recipe.ingredients}</p>
              <div className="recipe-actions">
                <button onClick={() => window.location.href = `/recipes/${recipe.id}`}>
                  Voir les détails
                </button>
                <button onClick={() => handleDelete(recipe.id)} className="delete-btn">
                  Supprimer
                </button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default RecipeList; 