import { useCallback, useEffect, useState } from 'react'; import { Alert } from 'react-native'; import * as authService from '../services/auth'; import cartService, { AddToCartRequest, CartResponse } from '../services/cart'; export const useCart = () => { const [cart, setCart] = useState(null); const [loading, setLoading] = useState(false); const [refreshing, setRefreshing] = useState(false); // Lấy userId từ auth service const getUserId = async (): Promise => { try { const isAuthenticated = await authService.isAuthenticated(); if (!isAuthenticated) { console.log('User is not authenticated'); return null; } const user = await authService.getUser(); console.log('getUserId - User data:', user); if (user && typeof user.userId === 'number') { return user.userId; } if (user) { console.warn('User exists but userId is missing or invalid:', user); } return null; } catch (error) { console.error('Error getting userId:', error); return null; } }; // Tải giỏ hàng const loadCart = useCallback(async () => { try { setLoading(true); const userId = await getUserId(); if (!userId) { setCart(null); return; } const data = await cartService.getCart(userId); setCart(data); } catch (error: any) { console.error('Load cart error:', error); const errorMessage = error?.message || ''; if (errorMessage.includes('404') || errorMessage.includes('Not Found') || errorMessage.includes('not found')) { setCart(null); } else if (!errorMessage.includes('User not logged in')) { console.warn('Failed to load cart:', errorMessage); } } finally { setLoading(false); } }, []); // Refresh giỏ hàng const refreshCart = useCallback(async () => { try { setRefreshing(true); await loadCart(); } finally { setRefreshing(false); } }, [loadCart]); // Thêm sản phẩm vào giỏ hàng const addToCart = useCallback(async (productId: number, quantity: number = 1) => { try { console.log('=== useCart: addToCart START ===', { productId, quantity }); const userId = await getUserId(); if (!userId) { Alert.alert('Thông báo', 'Vui lòng đăng nhập để thêm vào giỏ hàng'); return false; } const updatedCart = await cartService.addToCart(userId, { productId, quantity }); console.log('=== useCart: addToCart SUCCESS - Setting cart ===', updatedCart); setCart(updatedCart); // Cập nhật state ngay lập tức Alert.alert('Thành công', 'Đã thêm sản phẩm vào giỏ hàng'); return true; } catch (error: any) { console.error('=== useCart: addToCart ERROR ===', error); Alert.alert('Lỗi', 'Không thể thêm sản phẩm vào giỏ hàng'); return false; } }, []); // Cập nhật số lượng sản phẩm const updateQuantity = useCallback(async (cartItemId: number, quantity: number) => { try { const userId = await getUserId(); if (!userId) return false; const updatedCart = await cartService.updateCartItem(userId, cartItemId, { quantity }); setCart(updatedCart); // Cập nhật state ngay lập tức return true; } catch (error) { console.error('Update quantity error:', error); Alert.alert('Lỗi', 'Không thể cập nhật số lượng'); return false; } }, []); // Xóa một sản phẩm const removeItem = useCallback(async (cartItemId: number) => { try { const userId = await getUserId(); if (!userId) return false; const updatedCart = await cartService.removeCartItem(userId, cartItemId); setCart(updatedCart); // Cập nhật state ngay lập tức Alert.alert('Thành công', 'Đã xóa sản phẩm khỏi giỏ hàng'); return true; } catch (error) { console.error('Remove item error:', error); Alert.alert('Lỗi', 'Không thể xóa sản phẩm'); return false; } }, []); // Xóa tất cả sản phẩm const clearCart = useCallback(async () => { try { const userId = await getUserId(); if (!userId) return false; await cartService.clearCart(userId); setCart(null); Alert.alert('Thành công', 'Đã xóa tất cả sản phẩm'); return true; } catch (error) { console.error('Clear cart error:', error); Alert.alert('Lỗi', 'Không thể xóa giỏ hàng'); return false; } }, []); // Load cart khi component mount useEffect(() => { loadCart(); }, [loadCart]); return { cart, loading, refreshing, loadCart, refreshCart, addToCart, updateQuantity, removeItem, clearCart, }; };