import { View, Text, ScrollView, Image, TouchableOpacity, ActivityIndicator, Alert, RefreshControl } from 'react-native'
import React, { useEffect, useState, useCallback } from 'react'
import TabBar from '../themes/TabBar'
import { ChevronLeftIcon } from 'react-native-heroicons/outline'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { MapPinIcon } from 'react-native-heroicons/micro';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useNavigation } from '@react-navigation/native';
import { checkoutCart, getCart } from '../api';
export default function CheckOutScreen() {
const navigation = useNavigation();
const [cart, setCart] = useState({ items: [], total_price: 0 });
const [loading, setLoading] = useState(true);
const [placingOrder, setPlacingOrder] = useState(false);
const [error, setError] = useState(null);
const [refreshing, setRefreshing] = useState(false);
// Default shipping address
const shippingAddress = {
type: 'Home',
address: '1901 Thornridge Cir. Shiloh, Hawaii',
zipCode: '06803'
};
// Default shipping method
const shippingMethod = {
type: 'Economy',
estimatedArrival: '25 August 2023'
};
// Calculate item subtotal
const calculateSubtotal = (item) => {
// Ensure price and quantity exist and are numbers
const price = typeof item.price === 'number' ? item.price : 0;
const quantity = typeof item.quantity === 'number' ? item.quantity : 0;
return price * quantity;
};
// Process cart data to ensure all items have the required properties
const processCartData = (cartData) => {
if (!cartData || !cartData.items) {
return { items: [], total_price: 0 };
}
// Process each item to ensure it has the required properties
const processedItems = cartData.items.map(item => {
// Calculate subtotal if not provided by the backend
if (!item.subtotal || typeof item.subtotal !== 'number') {
item.subtotal = calculateSubtotal(item);
}
// Ensure other required properties exist
return {
...item,
id: item.id || Date.now(), // Fallback ID if not provided
product_name: item.product_name || item.name || item.title || 'Unknown Product',
product_image: item.product_image || item.image || 'https://via.placeholder.com/150',
price: typeof item.price === 'number' ? item.price : 0,
quantity: typeof item.quantity === 'number' ? item.quantity : 1
};
});
// Calculate total price if not provided or if we want to ensure it's correct
const total_price = processedItems.reduce((total, item) => total + item.subtotal, 0);
return {
items: processedItems,
total_price
};
};
const fetchCartData = async () => {
try {
setLoading(true);
const cartData = await getCart();
const processedCart = processCartData(cartData);
setCart(processedCart);
setError(null);
} catch (error) {
console.error('Error fetching cart:', error);
setError('Failed to load cart data');
} finally {
setLoading(false);
setRefreshing(false);
}
};
const onRefresh = useCallback(() => {
setRefreshing(true);
fetchCartData();
}, []);
useEffect(() => {
fetchCartData();
}, []);
const handlePlaceOrder = async () => {
if (!cart.items || cart.items.length === 0) {
Alert.alert('Empty Cart', 'Your cart is empty. Add some items before checking out.');
return;
}
try {
setPlacingOrder(true);
// Prepare order data
const orderData = {
shipping_address: `${shippingAddress.address}, ${shippingAddress.zipCode}`,
shipping_method: shippingMethod.type,
};
// Place the order using checkout endpoint
const response = await checkoutCart(orderData);
// Navigate to success screen
navigation.navigate('Payment Success', { orderId: response.id || response.order_id });
} catch (error) {
console.error('Error placing order:', error);
Alert.alert('Checkout Failed', 'Failed to place your order. Please try again.');
} finally {
setPlacingOrder(false);
}
};
if (loading) {
return (
);
}
if (error) {
return (
{error}
Retry
);
}
if (!cart.items || cart.items.length === 0) {
return (
Your cart is empty
navigation.navigate('Home')}
className="bg-primary py-2 px-4 rounded-lg"
>
Continue Shopping
);
}
// Calculate costs
const deliveryFee = 10;
const discountPercentage = 6;
const discount = (cart.total_price * discountPercentage) / 100;
const totalCost = cart.total_price + deliveryFee - discount;
return (
}
titleStyle={{
color: "black",
fontWeight: "bold",
fontSize: 20
}}
prefixStyle={{
backgroundColor: "transparent"
}}
suffixStyle={{
backgroundColor: "white",
borderWidth: 1,
borderColor: "black"
}}
containerStyle=""
suffixAction={() => navigation.goBack()}
/>
}
>
Shipping Address
{shippingAddress.type}
{shippingAddress.address}
{navigation.navigate('Shipping Address')}}>
CHANGE
{shippingAddress.zipCode}
Choose Shipping Type
{shippingMethod.type}
Estimated arrival {shippingMethod.estimatedArrival}
{navigation.navigate('Choose Shipping')}}>
CHANGE
Order List
{cart.items.length} item{cart.items.length !== 1 ? 's' : ''}
{cart.items.map((item, index) => {
// Calculate the subtotal for safety
const itemSubtotal = calculateSubtotal(item);
return (
{item.product_name}
Quantity: {item.quantity}
$ {itemSubtotal.toFixed(2)}
);
})}
Sub-Total
${cart.total_price.toFixed(2)}
Delivery fee
${deliveryFee.toFixed(2)}
Discount
{discountPercentage}% (${discount.toFixed(2)})
Total Cost
${totalCost.toFixed(2)}
{placingOrder ? (
) : (
Continue to Payment
)}
);
}