import { useEffect, useMemo, useState } from "react";
import ProductCard from "../components/ProductCard";
import { fetchProducts } from "../api/productsApi";

function ProductsPage() {
  const [products, setProducts] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [cartCount, setCartCount] = useState(0);

  useEffect(() => {
    let isMounted = true;

    async function loadProducts() {
      try {
        setLoading(true);
        setError("");
        const data = await fetchProducts();

        if (isMounted) {
          setProducts(data);
        }
      } catch (requestError) {
        if (isMounted) {
          setError("Az adatok betoltese nem sikerult. Probald ujra kesobb.");
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    loadProducts();

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

  const filteredProducts = useMemo(() => {
    return products.filter((product) =>
      product.title.toLowerCase().includes(searchTerm.trim().toLowerCase())
    );
  }, [products, searchTerm]);

  return (
    <section className="panel">
      <h2>Termekek</h2>
      <p>A kosarban levo termekek szama: {cartCount}</p>

      <label htmlFor="search">Szures nev alapjan</label>
      <input
        id="search"
        type="text"
        value={searchTerm}
        onChange={(event) => setSearchTerm(event.target.value)}
        placeholder="Pl. backpack"
      />

      {loading && <p>Betoltes folyamatban...</p>}
      {!loading && error && <p className="error-message">{error}</p>}
      {!loading && !error && filteredProducts.length === 0 && <p>Nincs talalat.</p>}

      <div className="product-grid">
        {filteredProducts.map((product) => (
          <ProductCard
            key={product.id}
            product={product}
            onAddToCart={() => setCartCount((current) => current + 1)}
          />
        ))}
      </div>
    </section>
  );
}

export default ProductsPage;
