'use client'; import React, { useEffect, useState } from 'react'; import { apiClient } from '@/app/utils/apiClient'; import Image from 'next/image'; import Link from 'next/link'; import { useCart } from '@/app/context/CartContext'; import { toast } from 'react-hot-toast'; import { useRouter } from 'next/navigation'; import '../category.scss'; interface ProductMedia { id: number; media_type: string; is_primary: boolean; media_data: string; } interface ProductType { id: number; product_name: string; product_price: number | string; product_discount_active: boolean; product_discount_price: number | string; product_discount_percentage: number | string; media?: ProductMedia[]; product_description: string; product_stock: number; } interface CategoryType { id: number; product_category: string; } export default function CategoryPage({ params }: { params: { name: string } }) { const [products, setProducts] = useState([]); const [category, setCategory] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const { addToCart } = useCart(); const router = useRouter(); useEffect(() => { const fetchCategoryProducts = async () => { try { setLoading(true); const categoryName = params.name; // First, find the category ID by name const categoriesResponse = await apiClient('/product/categories', { method: 'GET', skipAuth: true }); if (!categoriesResponse.success) { throw new Error('Failed to fetch categories'); } const matchedCategory = categoriesResponse.data.find( (cat: CategoryType) => cat.product_category.toLowerCase() === categoryName.toLowerCase() ); if (!matchedCategory) { setError(`Category "${categoryName}" not found`); setLoading(false); return; } setCategory(matchedCategory); // Then fetch products by category ID const response = await apiClient(`/product/products?category=${matchedCategory.id}`, { method: 'GET', skipAuth: true }); if (response && response.success && Array.isArray(response.data)) { setProducts(response.data); } else { throw new Error('Failed to fetch products'); } } catch (err) { console.error('Error fetching category products:', err); setError('Failed to load products. Please try again later.'); } finally { setLoading(false); } }; fetchCategoryProducts(); }, [params.name]); const formatPrice = (price: number | string): string => { if (price === null || price === undefined) return '0.00'; const numericPrice = typeof price === 'string' ? parseFloat(price) : price; if (isNaN(numericPrice)) return '0.00'; return numericPrice.toFixed(2); }; const getProductImage = (product: ProductType): string | null => { if (product.media && product.media.length > 0) { const primaryImage = product.media.find(m => m.is_primary); if (primaryImage) { return primaryImage.media_data; } return product.media[0].media_data; } return null; }; const calculateDiscount = (original: number | string, discounted: number | string): string => { const originalPrice = Number(original); const discountPrice = Number(discounted); if (originalPrice > 0 && discountPrice > 0) { const percentage = Math.round(((originalPrice - discountPrice) / originalPrice) * 100); return percentage.toString(); } return '0'; }; const handleAddToCart = (e: React.MouseEvent, product: ProductType) => { e.preventDefault(); e.stopPropagation(); addToCart(product); toast.success(`${product.product_name} added to cart`); }; const handleViewProduct = (e: React.MouseEvent, productId: number) => { e.preventDefault(); e.stopPropagation(); router.push(`/product/${productId}`); }; if (loading) { return (
Loading products...
); } if (error) { return (
{error}
View All Categories
); } return (

{category?.product_category || params.name}

{products.length} products found

{products.length === 0 ? (

No products found in this category.

Browse All Categories
) : (
{products.map((product) => (
{getProductImage(product) ? ( {product.product_name} ) : (
No image available
)} {product.product_discount_active && (
-{product.product_discount_percentage || calculateDiscount(product.product_price, product.product_discount_price)}%
)}

{product.product_name}

{product.product_discount_active ? (
${formatPrice(product.product_discount_price)} ${formatPrice(product.product_price)}
) : ( ${formatPrice(product.product_price)} )}
{product.product_stock <= 0 && (
Out of Stock
)}
))}
)}
); }