"use client";

import Link from "next/link";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import ProductProfile from "@/components/ProductProfile";

const API_BASE = "";

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

  useEffect(() => {
    if (!id) {
      return;
    }

    fetch(`${API_BASE}/api/v1/products/${id}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status} – ${res.statusText}`);
        }

        return res.json();
      })
      .then((data) => setProduct(data))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [id]);

  return (
    <main className="pet-detail-page">
      <div className="pet-detail-container">
        <Link href="/products" className="pet-detail-back">← Back to Products</Link>

        {loading && <p className="adopt-status-msg">Loading product details...</p>}
        {error && <p className="adopt-status-msg adopt-error">{error}</p>}

        {!loading && !error && product && (
          <ProductProfile
            prodId={product.prodId}
            prodName={product.prodName}
            categoryName={product.categoryName}
            prodDesc={product.prodDesc}
            prodPrice={product.prodPrice}
            imageUrl={product.imageUrl}
          />
        )}
      </div>
    </main>
  );
}
