import { View, Text, Image, ScrollView, TouchableOpacity, ActivityIndicator, Alert, TextInput } from 'react-native'
import React, { useEffect, useState, useCallback } from 'react'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import TabBar from '../themes/TabBar';
import { ChevronLeftIcon, HeartIcon, ShoppingBagIcon, StarIcon as StarOutlineIcon } from 'react-native-heroicons/outline'
import { StarIcon } from 'react-native-heroicons/solid';
import clothColor from '../constants/clothColor';
import { useNavigation, useRoute, useFocusEffect } from '@react-navigation/native';
import {
addToCartForCurrentUser,
fetchProductById,
fetchProductsByCategory,
getRecommendationsForCurrentUser,
toggleFavorite,
getFavorites,
rateProduct
} from '../api';
import ProductQuantityInput from '../components/ProductQuantityInput';
import FavoriteButton from '../components/FavoriteButton';
import { RefreshControl } from 'react-native';
export default function ProductDetailsScreen() {
const navigation = useNavigation();
const route = useRoute();
const { productId } = route.params || {};
const sizes = ["s", "m", "l", "xl", "xxl", "xxxl"];
const [selectedSize, setSelectedSize] = useState(0);
const [selectedColor, setSelectedColor] = useState(0);
const [product, setProduct] = useState(null);
const [relatedProducts, setRelatedProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [addingToCart, setAddingToCart] = useState(false);
const [error, setError] = useState(null);
const [quantity, setQuantity] = useState(1);
const [isFavorite, setIsFavorite] = useState(false);
const [userRating, setUserRating] = useState(0);
const [ratingComment, setRatingComment] = useState('');
const [submittingRating, setSubmittingRating] = useState(false);
const [showRatingForm, setShowRatingForm] = useState(false);
const [refreshing, setRefreshing] = useState(false);
// Load product data and check favorite status
const loadProductData = useCallback(async () => {
if (!productId) {
setError('Product ID is missing');
setLoading(false);
setRefreshing(false);
return;
}
try {
setLoading(true);
// Fetch product details
const productData = await fetchProductById(productId);
setProduct(productData);
// Check favorite status
const favorites = await getFavorites();
const isFavorited = favorites.some(fav => fav.id === parseInt(productId));
setIsFavorite(isFavorited);
// Get related products or recommendations
let related = [];
if (productData.category) {
const categoryProducts = await fetchProductsByCategory(productData.category);
related = categoryProducts
.filter(p => p.id !== productData.id)
.slice(0, 4);
}
if (related.length < 4) {
const recommendations = await getRecommendationsForCurrentUser(4 - related.length);
related = [...related, ...recommendations.filter(r => r.id !== productData.id)];
related = related.slice(0, 4);
}
setRelatedProducts(related);
setError(null);
} catch (error) {
console.error('Error loading product data:', error);
setError('Failed to load product details');
} finally {
setLoading(false);
setRefreshing(false);
}
}, [productId]);
const onRefresh = useCallback(() => {
setRefreshing(true);
loadProductData();
}, [loadProductData]);
// Load data when screen is focused
useFocusEffect(
useCallback(() => {
loadProductData();
}, [loadProductData])
);
const handleAddToCart = async () => {
if (!product) return;
try {
setAddingToCart(true);
const productWithOptions = {
...product,
selectedSize: sizes[selectedSize],
selectedColor: clothColor[selectedColor].name
};
await addToCartForCurrentUser(productWithOptions, quantity);
Alert.alert(
'Added to Cart',
`${product.title} has been added to your cart.`,
[
{
text: 'Continue Shopping',
style: 'cancel',
},
{
text: 'View Cart',
onPress: () => navigation.navigate('My Cart'),
},
]
);
} catch (error) {
console.error('Error adding to cart:', error);
Alert.alert('Error', 'Failed to add item to cart. Please try again.');
} finally {
setAddingToCart(false);
}
};
// Handle favorite toggle
const handleToggleFavorite = async (newFavoriteState) => {
setIsFavorite(newFavoriteState);
};
// Increase quantity
const increaseQuantity = () => {
setQuantity(prevQuantity => prevQuantity + 1);
};
// Decrease quantity (minimum 1)
const decreaseQuantity = () => {
setQuantity(prevQuantity => Math.max(1, prevQuantity - 1));
};
// Handle rating submission
const handleSubmitRating = async () => {
if (userRating === 0) {
Alert.alert("Error", "Please select a rating");
return;
}
try {
setSubmittingRating(true);
await rateProduct(productId, userRating, ratingComment);
Alert.alert("Success", "Your rating has been submitted");
setUserRating(0);
setRatingComment('');
setShowRatingForm(false);
// Refresh product data to show updated rating
const updatedProduct = await fetchProductById(productId);
setProduct(updatedProduct);
} catch (error) {
console.error('Error submitting rating:', error);
Alert.alert("Error", "Failed to submit rating. Please try again.");
} finally {
setSubmittingRating(false);
}
};
// Display loading state
if (loading) {
return (
);
}
// Display error state
if (error || !product) {
return (
{error || 'Product not found'}
navigation.goBack()}
className="bg-primary py-2 px-4 rounded-lg"
>
Go Back
);
}
return (
}
>
}
title={product.title}
suffix={}
titleStyle={{
color: "white",
fontWeight: "bold",
fontSize: 15
}}
prefixStyle={{
backgroundColor: "transparent"
}}
suffixStyle={{
backgroundColor: "gray"
}}
containerStyle="absolute z-[3] top-0"
suffixAction={() => navigation.goBack()}
/>
{product.category}
{product.rating?.rate || '4.0'}
{product.title}
Product Details
{product.description?.length > 150
? `${product.description.substring(0, 150)}...`
: product.description}
Read More
Select Sizes
{
sizes.map((item, index) => {
let isActive = index == selectedSize;
return (
setSelectedSize(index)}
className={`px-4 py-2 rounded-xl
${isActive ? "bg-primary border border-primary" : " border"}`
}>
{item}
);
})
}
Select Color
{
clothColor.map((item, index) => {
let isActive = index == selectedColor;
return (
setSelectedColor(index)}
className={`px-4 py-2 rounded-xl
${isActive ? "bg-primary border border-primary" : " border"}`
}>
{item.name}
);
})
}
Quantity
Related Products
{relatedProducts.map((item, index) => (
navigation.navigate('ProductDetails', { productId: item.id })}
className="w-[150px] h-[200px] rounded-xl border"
>
{item.title}
${item.price}
))}
{/* Rating Section */}
Ratings & Reviews
setShowRatingForm(!showRatingForm)}
className="bg-primary px-3 py-1 rounded-full"
>
Rate this product
{showRatingForm && (
Your Rating
{[1, 2, 3, 4, 5].map(star => (
setUserRating(star)}
className="mr-2"
>
{userRating >= star ? (
) : (
)}
))}
Comment (optional)
{submittingRating ? (
) : (
Submit Rating
)}
)}
{/* Display existing ratings */}
{product.ratings && product.ratings.length > 0 ? (
{product.ratings.map((rating, index) => (
{[1, 2, 3, 4, 5].map(star => (
))}
{rating.username}
{new Date(rating.created_at).toLocaleDateString()}
{rating.comment && (
{rating.comment}
)}
))}
) : (
No ratings yet. Be the first to rate this product!
)}
Total Price
${(product.price * quantity).toFixed(2)}
{addingToCart ? (
) : (
<>
Add to Cart
>
)}
);
}