import { View, Text, Image, TouchableOpacity, ActivityIndicator, Alert } from 'react-native'
import React, { useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import { fetchProductById } from '../api'
export default function ActiveOrder({ orders = [], navigation: propNavigation }) {
// Use provided navigation prop if available, otherwise get from hook
const navigation = propNavigation || useNavigation();
const [loading, setLoading] = useState(false);
// Safe number formatting helper
const formatCurrency = (value) => {
if (value === undefined || value === null) return '0.00';
if (typeof value === 'number') return value.toFixed(2);
if (typeof value === 'string') {
const num = parseFloat(value);
return isNaN(num) ? '0.00' : num.toFixed(2);
}
return '0.00';
};
const handleReOrder = async (order) => {
console.log('Order data:', order);
// Use order_items as primary source, fallback to items if order_items is empty
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
console.log('Order items:', orderItems);
if (!orderItems || orderItems.length === 0) {
Alert.alert('Error', 'No items found in this order');
return;
}
try {
setLoading(true);
const firstItem = orderItems[0];
console.log('First item:', firstItem);
const productId = firstItem.product || firstItem.product_id || firstItem.id;
console.log('Product ID:', productId);
if (!productId) {
Alert.alert('Error', 'Could not find product ID');
return;
}
const product = await fetchProductById(productId);
console.log('Fetched product:', product);
if (!product) {
Alert.alert('Error', 'Product not found');
return;
}
navigation.navigate('ProductDetails', { id: product.id });
} catch (error) {
console.error('Error in handleReOrder:', error);
Alert.alert('Error', 'Failed to load product details. Please try again.');
} finally {
setLoading(false);
}
};
if (!orders || orders.length === 0) {
return (
No active orders found
);
}
return (
{orders.map((order, index) => {
const orderItems = (order.order_items && order.order_items.length > 0) ? order.order_items : order.items;
return (
Order #{order.id}
{new Date(order.created_at || order.date).toLocaleDateString()} |
Status: {order.status}
{orderItems && orderItems.map((item, itemIndex) => (
{item.product_name || item.product?.title || 'Product'}
Qty: {item.quantity}
${formatCurrency(item.price || item.subtotal)}
))}
Total: ${formatCurrency(order.total_price || order.total_amount)}
navigation.navigate('Track Order', { orderId: order.id })}
className={`bg-primary rounded-full px-4 py-2`}
>
Track Order
);
})}
);
}
const styles = {
itemImage: {
width: 90,
height: 90,
borderRadius: 10,
},
}