"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 = "";

//Product detail page, fetches a single product by ID and passes it to ProductProfile
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="min-h-screen py-12 px-8 pb-20">
      <div className="max-w-[860px] mx-auto">
        <Link href="/products" className="inline-block mb-8 text-[#e68672] no-underline text-base font-semibold transition-colors hover:text-[#d4705e]">← Back to Products</Link>

        {loading && <p className="text-center text-[#666] text-[1.1rem] py-12">Loading product details...</p>}
        {error && <p className="text-center text-[#c0392b] text-[1.1rem] py-12">{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>
  );
}
