'use client';

import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import ProductDetailsWithAPI from '@/components/ProductDetail/ProductDetailsWithAPI';
import ProductReviews from "@/components/ProductDetail/ProductReviews";
import YouMightAlsoLike from "@/components/ProductDetail/YouMightAlsoLike";
import SearchCTA from "@/components/SearchCTA";
import { ProductDetailService } from '@/services/productDetailService';

export default function ProductDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  const [categoryId, setCategoryId] = useState<number | undefined>();
  const [productId, setProductId] = useState<number | undefined>();
  const [productName, setProductName] = useState<string>('');

  // Fetch product data to get category ID
  useEffect(() => {
    const fetchProductInfo = async () => {
      try {
        const product = await ProductDetailService.getProductBySlug(slug);
        setCategoryId(product.category.id);
        setProductId(product.id);
        setProductName(product.name);
      } catch (error) {
        console.error('Failed to fetch product info:', error);
      }
    };

    if (slug) {
      fetchProductInfo();
    }
  }, [slug]);

  return (
    <div className="pt-6 sm:pt-9">
      <ProductDetailsWithAPI slug={slug} />
      <ProductReviews productId={productId} productName={productName} />
      <YouMightAlsoLike categoryId={categoryId} currentProductId={productId} />
      <SearchCTA />
    </div>
  );
}