import { useState, useEffect } from "react";
import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
import { getRecipes, deleteRecipe } from "../services/frontendApi.js";




function Search() {
  const [searchQuery, setSearchQuery] = useState("");
  const [recipes, setRecipes] = useState([]);
  const [cuisines, setCuisines] = useState([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
  const [selectedCuisine, setSelectedCuisine] = useState("");

  useEffect(() => {
    const loadRecipes = async () => {
      try {
        const recipes = await getRecipes();
        setRecipes(recipes);
        console.log(recipes)
        const uniqueCuisines: [] = Array.from(new Set(recipes.map(recipe => recipe.cuisine)))
        setCuisines(uniqueCuisines)
        console.log(cuisines)
      } catch (error) {
        console.log(error);
        setError("Failed to load recipes...");
      } finally {
        setLoading(false);
      }
    };
    if (shouldFetchRecipes) {
      loadRecipes().then(() => setShouldFetchRecipes(false));
    }
  }, [shouldFetchRecipes]);

  const handleDelete = async (id: number | void) => {
    try {
      await deleteRecipe(id);
      setShouldFetchRecipes(true);
    } catch (error) {
      console.error("Error deleting recipe:", error);
    }
  };
  const filteredRecipes = selectedCuisine ? recipes.filter(recipe => recipe.cuisine === selectedCuisine) : recipes;

  return (
    <div className="add-recipe-card bg-amber-100 border border-amber-200 rounded-bl-lg rounded-br-lg p-6 md:p-8 lg:p-10 max-w-6xl mx-auto font-serif">
      <div className="cuisines-buttons flex flex-wrap justify-center">
        <input
          type="text"
          placeholder="name"
          className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        {cuisines.map((cuisine) => (
          <button
            key={cuisine}
            className={`ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700 m-2 ${selectedCuisine === cuisine ? 'selected bg-amber-800' : ''}`}
            onClick={() => setSelectedCuisine((prevState => prevState === cuisine ? "" : cuisine))}
          >
            {cuisine}
          </button>
        ))}
      </div>      {error && <div className="error-message">{error}</div>}
      {loading ? (
        <div className="loading">Loading...</div>
      ) : (
        <div className="recipe-outer bg-amber-100 p-4 md:p-8 lg:p-12">
          <div className="recipes-grid grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">
            {filteredRecipes.map((recipe) => (
              recipe.name.toLowerCase().startsWith(searchQuery) &&
              <CookbookRecipeTile recipe={recipe} key={recipe.id} handleDelete={handleDelete} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

export default Search
