import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import type { Recipe } from '../services/api';
import { recipeApi, imageApi } from '../services/api';
import './RecipeList.css';

// Debounce hook
const useDebounce = (value: string, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};

const RecipeList: React.FC = () => {
  const [recipes, setRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(true);
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState('');
  const [page, setPage] = useState(1);
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 10,
    total: 0,
    pages: 0,
  });

  // Debounce search to prevent too many API calls
  const debouncedSearch = useDebounce(search, 300);

  const loadRecipes = async () => {
    try {
      if (recipes.length > 0) {
        setIsSearching(true); // Show subtle loading for subsequent searches
      }
      setError(null); // Clear previous errors
      const response = await recipeApi.getRecipes({
        search: debouncedSearch || undefined,
        category: category || undefined,
        page,
        limit: 12,
        sortBy: 'title',
        sortOrder: 'asc',
      });

      if (response.success) {
        setRecipes(response.data);
        setPagination(response.pagination);
      } else {
        setError('Fehler beim Laden der Rezepte');
      }
    } catch (err) {
      setError('Verbindungsfehler - Ist der Server gestartet?');
      console.error('Error loading recipes:', err);
    } finally {
      setLoading(false);
      setIsSearching(false);
    }
  };

  useEffect(() => {
    loadRecipes();
  }, [debouncedSearch, category, page]);

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(1);
    loadRecipes();
  };

  const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setCategory(e.target.value);
    setPage(1);
  };

  if (loading) {
    return (
      <div className="recipe-list">
        <div className="loading">Lade Rezepte...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="recipe-list">
        <div className="error">
          <h3>Fehler</h3>
          <p>{error}</p>
          <button onClick={loadRecipes} className="retry-button">
            Erneut versuchen
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="recipe-list">
      <div className="recipe-list-header">
        <h2>
          Alle Rezepte ({pagination.total})
          {isSearching && <span className="searching-indicator"> 🔍</span>}
        </h2>
        
        <div className="filters">
          <form onSubmit={handleSearchSubmit} className="search-form">
            <input
              type="text"
              placeholder="Rezepte durchsuchen..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="search-input"
            />
            <button type="submit" className="search-button">
              🔍
            </button>
          </form>

          <select
            value={category}
            onChange={handleCategoryChange}
            className="category-select"
          >
            <option value="">Alle Kategorien</option>
            <option value="Vegan">Vegan</option>
            <option value="Vegetarisch">Vegetarisch</option>
            <option value="Fleisch">Fleisch</option>
            <option value="Fisch">Fisch</option>
            <option value="Dessert">Dessert</option>
          </select>
        </div>
      </div>

      <div className="recipes-grid">
        {recipes.map((recipe) => (
          <div key={recipe.id} className="recipe-card">
            <div className="recipe-image">
              {recipe.images && recipe.images.length > 0 ? (
                <img 
                  src={imageApi.getImageUrl(recipe.images[0].filePath)}
                  alt={recipe.title}
                  loading="lazy"
                  style={{ 
                    width: '100%', 
                    height: '100%', 
                    objectFit: 'cover',
                    display: 'block'
                  }}
                  onError={(e) => {
                    const imgSrc = recipe.images?.[0]?.filePath 
                      ? imageApi.getImageUrl(recipe.images[0].filePath)
                      : 'unknown';
                    console.error('Failed to load image:', imgSrc);
                    e.currentTarget.style.display = 'none';
                    e.currentTarget.parentElement!.innerHTML = '<div class="no-image">📸</div>';
                  }}
                />
              ) : (
                <div className="no-image">📸</div>
              )}
            </div>
            
            <div className="recipe-content">
              <h3 className="recipe-title">{recipe.title}</h3>
              <p className="recipe-description">
                {recipe.description ? 
                  recipe.description.length > 100 ? 
                    recipe.description.substring(0, 100) + '...' : 
                    recipe.description 
                  : 'Keine Beschreibung verfügbar'
                }
              </p>
              
              <div className="recipe-meta">
                {recipe.category && (
                  <span className="recipe-category">{recipe.category}</span>
                )}
                <span className="recipe-servings">👥 {recipe.servings} Portionen</span>
              </div>
              
              <div className="recipe-actions">
                <Link to={`/recipes/${recipe.id}`} className="view-button">
                  Ansehen
                </Link>
                <Link to={`/recipes/${recipe.id}/edit`} className="edit-button">
                  Bearbeiten
                </Link>
              </div>
            </div>
          </div>
        ))}
      </div>

      {recipes.length === 0 && (
        <div className="no-recipes">
          <h3>Keine Rezepte gefunden</h3>
          <p>Versuche es mit anderen Suchbegriffen oder erstelle ein neues Rezept.</p>
          <Link to="/recipes/new" className="create-button">
            Neues Rezept erstellen
          </Link>
        </div>
      )}

      {pagination.pages > 1 && (
        <div className="pagination">
          <button
            onClick={() => setPage(page - 1)}
            disabled={page <= 1}
            className="pagination-button"
          >
            ← Vorherige
          </button>
          
          <span className="pagination-info">
            Seite {page} von {pagination.pages}
          </span>
          
          <button
            onClick={() => setPage(page + 1)}
            disabled={page >= pagination.pages}
            className="pagination-button"
          >
            Nächste →
          </button>
        </div>
      )}
    </div>
  );
};

export default RecipeList;