import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { listRecipes, uploadedImageUrl } from "../api/client";
import type { RecipeSummary } from "../types/recipe";

export default function RecipeListPage() {
  const [recipes, setRecipes] = useState<RecipeSummary[]>([]);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const handle = setTimeout(() => {
      setLoading(true);
      listRecipes(search)
        .then(setRecipes)
        .catch((e) => setError(e.message))
        .finally(() => setLoading(false));
    }, 200);
    return () => clearTimeout(handle);
  }, [search]);

  return (
    <div className="page">
      <div className="page-header">
        <h1>Rezepte</h1>
        <Link className="button primary" to="/recipes/new">+ Neues Rezept</Link>
      </div>

      <input
        className="search"
        placeholder="Suche nach Name oder Kategorie…"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />

      {error && <p className="error">{error}</p>}
      {loading && <p>Lädt…</p>}

      <div className="recipe-grid">
        {recipes.map((recipe) => (
          <Link key={recipe.id} to={`/recipes/${recipe.id}`} className="recipe-card">
            {recipe.image_filename ? (
              <img src={uploadedImageUrl(recipe.image_filename)} alt="" />
            ) : (
              <div className="recipe-card-placeholder" />
            )}
            <div className="recipe-card-body">
              <strong>{recipe.name}</strong>
              {recipe.category && <span className="tag">{recipe.category}</span>}
            </div>
          </Link>
        ))}
        {!loading && recipes.length === 0 && <p>Keine Rezepte gefunden.</p>}
      </div>
    </div>
  );
}
