import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { fetchProductById } from "../api/productsApi";

function ProductDetailsPage() {
  const { id } = useParams();
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

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

    async function loadProduct() {
      try {
        setLoading(true);
        setError("");
        const data = await fetchProductById(id);

        if (isMounted) {
          setProduct(data);
        }
      } catch (requestError) {
        if (isMounted) {
          setError("A termek adatainak betoltese nem sikerult.");
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    loadProduct();

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

  if (loading) {
    return <p>Betoltes folyamatban...</p>;
  }

  if (error) {
    return <p className="error-message">{error}</p>;
  }

  if (!product) {
    return <p>Nincs ilyen termek.</p>;
  }

  return (
    <section className="panel details-page">
      <Link to="/termekek">Vissza a listahoz</Link>
      <h2>{product.title}</h2>
      <img src={product.image} alt={product.title} />
      <p>Kategoria: {product.category}</p>
      <p>{product.description}</p>
      <strong>{product.price.toFixed(2)} USD</strong>
    </section>
  );
}

export default ProductDetailsPage;
