ifixkart-storefront/components/pdp/ProductReviewsSection.tsx

191 lines
6.8 KiB
TypeScript

'use client';
import React, { useState, useEffect } from 'react';
import { ChevronDown, MessageSquare, Loader2 } from 'lucide-react';
import { reviewService, ProductReviewItem, ProductReviewSummaryResponse } from '@/services/api/reviewService';
import { ReviewSummaryBreakdown } from './ReviewSummaryBreakdown';
import { ReviewCard } from './ReviewCard';
import { ReviewSubmissionModal } from './ReviewSubmissionModal';
interface ProductReviewsSectionProps {
productId: string;
productName: string;
onReviewsCountChange?: (count: number) => void;
}
export function ProductReviewsSection({
productId,
productName,
onReviewsCountChange,
}: ProductReviewsSectionProps) {
const [data, setData] = useState<ProductReviewSummaryResponse | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [sort, setSort] = useState('newest');
const [page, setPage] = useState(1);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isLoadingMore, setIsLoadingMore] = useState(false);
useEffect(() => {
setIsLoading(true);
reviewService
.getProductReviews(productId, 1, 10, sort)
.then((res) => {
setData(res);
if (onReviewsCountChange) onReviewsCountChange(res.total_reviews);
})
.finally(() => {
setIsLoading(false);
});
}, [productId, sort]);
const handleLoadMore = () => {
if (!data) return;
setIsLoadingMore(true);
const nextPage = page + 1;
reviewService
.getProductReviews(productId, nextPage, 10, sort)
.then((res) => {
setData((prev) => {
if (!prev) return res;
return {
...res,
reviews: [...prev.reviews, ...res.reviews],
};
});
setPage(nextPage);
})
.finally(() => {
setIsLoadingMore(false);
});
};
const handleReviewSubmitted = (newReview: ProductReviewItem) => {
setData((prev) => {
const existingReviews = prev ? prev.reviews : [];
const updatedReviews = [newReview, ...existingReviews];
const newTotal = (prev?.total_reviews || 0) + 1;
const starKey = String(newReview.rating);
const newDist = { ...(prev?.star_distribution || {}) };
newDist[starKey] = (newDist[starKey] || 0) + 1;
if (onReviewsCountChange) onReviewsCountChange(newTotal);
return {
average_rating: prev ? ((prev.average_rating * prev.total_reviews) + newReview.rating) / newTotal : newReview.rating,
total_reviews: newTotal,
star_distribution: newDist,
verified_count: (prev?.verified_count || 0) + (newReview.verified_buyer ? 1 : 0),
page: 1,
limit: 10,
reviews: updatedReviews,
};
});
};
if (isLoading) {
return (
<div className="py-12 flex flex-col items-center justify-center gap-3">
<Loader2 size={24} className="text-primary animate-spin" />
<p className="text-xs font-semibold text-gray-500">Loading customer reviews...</p>
</div>
);
}
const reviews = data?.reviews || [];
const totalReviews = data?.total_reviews || 0;
const averageRating = data?.average_rating || 0;
const verifiedCount = data?.verified_count || 0;
const starDistribution = data?.star_distribution || { '5': 0, '4': 0, '3': 0, '2': 0, '1': 0 };
const hasMore = reviews.length < totalReviews;
return (
<div className="py-4">
{/* 1. Summary Breakdown */}
<ReviewSummaryBreakdown
averageRating={averageRating}
totalReviews={totalReviews}
verifiedCount={verifiedCount}
starDistribution={starDistribution}
onWriteReviewClick={() => setIsModalOpen(true)}
/>
{/* 2. Reviews Header with Sorting */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-gray-200 mb-2">
<h3 className="text-sm font-bold text-gray-900">
Customer Feedback ({totalReviews})
</h3>
{reviews.length > 0 && (
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 font-medium">Sort by:</span>
<div className="relative">
<select
value={sort}
onChange={(e) => setSort(e.target.value)}
className="appearance-none bg-white border border-gray-300 rounded-md pl-3 pr-7 py-1.5 text-xs font-medium text-gray-700 cursor-pointer focus:outline-none focus:border-primary"
>
<option value="newest">Most Recent</option>
<option value="highest">Highest Rating</option>
<option value="lowest">Lowest Rating</option>
<option value="helpful">Most Helpful</option>
</select>
<ChevronDown
size={12}
className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"
/>
</div>
</div>
)}
</div>
{/* 3. Review Cards List */}
{reviews.length === 0 ? (
<div className="py-12 text-center space-y-3">
<MessageSquare size={36} className="mx-auto text-gray-300" />
<h4 className="text-sm font-bold text-gray-800">No reviews yet</h4>
<p className="text-xs text-gray-500 max-w-sm mx-auto">
Have you purchased this product? Be the first to share your thoughts with other customers.
</p>
<button
type="button"
onClick={() => setIsModalOpen(true)}
className="px-5 py-2.5 bg-primary text-white text-xs font-bold rounded-lg hover:brightness-95 shadow-sm inline-flex items-center gap-2 cursor-pointer mt-2"
>
Write the First Review
</button>
</div>
) : (
<div className="divide-y divide-gray-100">
{reviews.map((r) => (
<ReviewCard key={r.review_id} review={r} />
))}
</div>
)}
{/* 4. Load More Button */}
{hasMore && (
<div className="pt-6 flex justify-center">
<button
type="button"
onClick={handleLoadMore}
disabled={isLoadingMore}
className="px-6 py-2.5 border border-gray-300 text-gray-700 text-xs font-semibold rounded-lg hover:bg-gray-50 transition-colors cursor-pointer disabled:opacity-60 inline-flex items-center gap-2"
>
{isLoadingMore && <Loader2 size={13} className="animate-spin" />}
<span>{isLoadingMore ? 'Loading...' : 'Load More Reviews'}</span>
</button>
</div>
)}
{/* 5. Submission Modal */}
<ReviewSubmissionModal
productId={productId}
productName={productName}
isOpen={isModalOpen}
onClose={() => setIsModalOpen(false)}
onReviewSubmitted={handleReviewSubmitted}
/>
</div>
);
}