'use client';

import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import TopNavOne from '@/components/Header/TopNav/TopNavOne';
import MenuOne from '@/components/Header/Menu/MenuOne';
import BreadcrumbProduct from '@/components/Breadcrumb/BreadcrumbProduct';
import Default from '@/components/Product/Detail/Default';
import Footer from '@/components/Footer/Footer';
import { ProductType } from '@/type/ProductType';
import axios from 'axios';
import { BaseURL } from '../../../utils/BaseUrl';

const ProductDefault = () => {
  const searchParams = useSearchParams();
  const productId = searchParams.get('id');

  // ✅ product should be a single object, not an array
  const [product, setProduct] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    if (productId) {
      fetchProduct(productId);
    }
  }, [productId]); // ✅ include productId in deps

  const fetchProduct = async (id: string) => {
    try {
      const response = await axios.get(`${BaseURL}/products/${id}`);
      console.log('response', response);
      setProduct(response?.data?.data || null);
    } catch (error) {
      console.error('❌ Error fetching product:', error);
    } finally {
      setLoading(false);
    }
  };

  console.log('product', product);

  if (loading) {
    return <div className="p-6 text-center">Loading product...</div>;
  }

  if (!product) {
    return <div className="p-6 text-center text-red-500">Product not found</div>;
  }

  return (
    <>
      <TopNavOne
        props="style-one bg-black"
        slogan="New customers save 10% with the code GET10"
      />
      <div id="header" className="relative w-full">
        <MenuOne props="bg-white" />
        <BreadcrumbProduct
          data={product}
          productPage="default"
          productId={productId || ''}
        />
      </div>
      <Default data={product} productId={productId || ''} />
      <Footer />
    </>
  );
};

export default ProductDefault;
