freshyo/apps/user-ui/components/CheckoutAddressSelector.tsx
2026-11-08 13:49:17 +05:30

332 lines
13 KiB
TypeScript

import React, { useState, useRef } from 'react';
import { View, Text, TouchableOpacity, ScrollView, Alert, NativeSyntheticEvent, NativeScrollEvent } from 'react-native';
import { useRouter } from 'expo-router';
import { tw, BottomDialog, RawBottomDialog, MyText } from 'common-ui';
import { useQueryClient } from '@tanstack/react-query';
import AddressForm from '@/src/components/AddressForm';
import LocationAttacher from '@/src/components/LocationAttacher';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { trpc } from '@/src/trpc-client';
import { useAuth } from '@/src/contexts/AuthContext';
import { useRegionNeo } from '@/src/hooks/useRegionNeo';
import { addressIconName, toNeoAddress } from '@/src/lib/neo-address';
import { useNeoRegionStore } from '@/src/store/neoRegionStore';
import * as Location from 'expo-location';
const CARD_WIDTH = 300; // 288 (w-72) + 12 (mr-3)
const CheckoutAddressSelector: React.FC = () => {
const neo = useRegionNeo();
const selectedAddress = neo.selectedAddressId;
const selectAddress = neo.selectAddress;
const setAddresses = useNeoRegionStore((state) => state.setAddresses);
const [showAddAddress, setShowAddAddress] = useState(false);
const [editingLocationAddressId, setEditingLocationAddressId] = useState<number | null>(null);
const [locationLoading, setLocationLoading] = useState(false);
const [currentIndex, setCurrentIndex] = useState(0);
const queryClient = useQueryClient();
const utils = trpc.useUtils();
const router = useRouter();
const scrollViewRef = useRef<ScrollView>(null);
// The region the add-address form resolved to, so a cross-region save can be
// confirmed before it switches (and clears the cart).
const resolvedRegionRef = useRef<{ regionId: number; boundId: number | null } | null>(null);
const { isAuthenticated } = useAuth();
const selectedRegionId = neo.regionId;
const { data: addresses } = trpc.user.address.getUserAddresses.useQuery(
undefined,
{ enabled: isAuthenticated }
);
const regions = useNeoRegionStore((state) => state.regions);
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
onSuccess: () => {
utils.user.address.getUserAddresses.invalidate();
setEditingLocationAddressId(null);
Alert.alert('Success', 'Location attached successfully');
},
onError: (error: any) => {
setEditingLocationAddressId(null);
Alert.alert('Error', error.message || 'Failed to attach location');
},
});
// Sort addresses with selected first, then default, then others
const sortedAddresses = React.useMemo(() => {
if (!addresses?.data) return [];
return [...addresses.data].sort((a, b) => {
// Selected address comes first
if (selectedAddress === a.id && selectedAddress !== b.id) return -1;
if (selectedAddress === b.id && selectedAddress !== a.id) return 1;
// Then default address (if not already selected)
if (a.isDefault && !b.isDefault) return -1;
if (!a.isDefault && b.isDefault) return 1;
// Maintain stable sort by id for other addresses
return a.id - b.id;
});
}, [addresses?.data, selectedAddress]);
// Reset scroll to left when address is selected
const resetScrollToLeft = () => {
setCurrentIndex(0);
scrollViewRef.current?.scrollTo({ x: 0, y: 0, animated: true });
};
const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
const index = Math.round(event.nativeEvent.contentOffset.x / CARD_WIDTH);
setCurrentIndex(index);
};
// Every cross-region selection goes through this confirmation, because the
// switch clears the cart for the current region.
// Adding or editing an address is the caller's job to refresh the list.
const refreshAddresses = async () => {
try {
const response = await utils.user.address.getUserAddresses.fetch(undefined);
if (response.data) setAddresses(response.data.map(toNeoAddress));
} catch {
// The form's mutation invalidation will refresh it.
}
};
const confirmSwitch = (regionName: string, onConfirm: () => void) => {
Alert.alert(
'Switch region?',
`This address is in ${regionName}. Switching will clear your entire cart and take you home.`,
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Switch & clear cart', style: 'destructive', onPress: onConfirm },
]
);
};
const handleAddressPress = (address: any) => {
if (selectedRegionId && address.regionId && address.regionId !== selectedRegionId) {
const targetRegion = (regions ?? []).find((region) => region.id === address.regionId);
if (!targetRegion) {
Alert.alert('Unavailable region', 'This address belongs to a region that is not currently available.');
return;
}
confirmSwitch(targetRegion.name, () => {
void (async () => {
await selectAddress(address.id);
router.replace('/(drawer)/(tabs)/home');
})();
});
return;
}
void selectAddress(address.id);
resetScrollToLeft();
};
const handleAttachLocation = async (address: any) => {
setEditingLocationAddressId(address.id);
setLocationLoading(true);
try {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
Alert.alert('Permission Denied', 'Location permission is required to attach your current location');
setLocationLoading(false);
setEditingLocationAddressId(null);
return;
}
const location = await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.High,
});
const { latitude, longitude } = location.coords;
updateAddressMutation.mutate({
id: address.id,
regionId: address.regionId ?? selectedRegionId ?? undefined,
name: address.name,
phone: address.phone,
addressLine1: address.addressLine1,
addressLine2: address.addressLine2 || '',
city: address.city,
state: address.state,
isDefault: address.isDefault,
latitude,
longitude,
});
} catch (error) {
Alert.alert('Error', 'Unable to fetch location. Please check your GPS settings.');
setLocationLoading(false);
setEditingLocationAddressId(null);
}
};
return (
<>
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<View style={tw`flex-row justify-between items-center mb-3`}>
<View style={tw`flex-row items-center`}>
<View
style={tw`w-8 h-8 bg-blue-50 rounded-full items-center justify-center mr-3`}
>
<MaterialIcons name="location-on" size={18} color="#3B82F6" />
</View>
<Text style={tw`text-base font-bold text-gray-900`}>
Delivery Address
</Text>
</View>
<TouchableOpacity testID="add-new-address" onPress={() => setShowAddAddress(true)}>
<Text style={tw`text-brand500 font-bold text-sm`}>+ Add New</Text>
</TouchableOpacity>
</View>
{(!sortedAddresses || sortedAddresses.length === 0) ? (
<View style={tw`bg-gray-50 p-6 rounded-xl border border-gray-200 border-dashed items-center justify-center`}>
<MaterialIcons name="location-off" size={32} color="#9CA3AF" />
<Text style={tw`text-gray-500 mt-2`}>No addresses found</Text>
<TouchableOpacity testID="add-address-empty" onPress={() => setShowAddAddress(true)} style={tw`mt-3 bg-brand500 px-4 py-2 rounded-lg`}>
<Text style={tw`text-white font-bold text-sm`}>Add Address</Text>
</TouchableOpacity>
</View>
) : (
<ScrollView
testID="address-scroll"
ref={scrollViewRef}
horizontal
showsHorizontalScrollIndicator={false}
style={tw`pb-2`}
onScroll={handleScroll}
onMomentumScrollEnd={handleScroll}
scrollEventThrottle={16}
decelerationRate="fast"
snapToInterval={CARD_WIDTH}
>
{sortedAddresses.map((address, index) => (
<TouchableOpacity
key={address.id}
testID={`address-option-${index}`}
onPress={() => handleAddressPress(address)}
style={tw`w-72 p-4 mr-3 bg-gray-50 rounded-xl border-2 ${selectedAddress === address.id ? 'border-brand500 bg-blue-50' : 'border-gray-200'
} shadow-sm`}
>
<View style={tw`flex-row justify-between items-start mb-2`}>
<View style={tw`flex-row items-center`}>
<MaterialIcons
name={addressIconName(address.name)}
size={20}
color={selectedAddress === address.id ? '#EC4899' : '#6B7280'}
/>
<Text style={tw`font-bold ml-2 ${selectedAddress === address.id ? 'text-brand500' : 'text-gray-900'}`}>
{address.name}
</Text>
</View>
{selectedAddress === address.id && (
<View style={tw`bg-brand500 w-5 h-5 rounded-full items-center justify-center`}>
<MaterialIcons name="check" size={14} color="white" />
</View>
)}
</View>
<Text style={tw`text-gray-600 text-sm leading-5 mb-1`} numberOfLines={2}>
{address.addressLine1}{address.addressLine2 ? `, ${address.addressLine2}` : ''}
</Text>
<Text style={tw`text-gray-600 text-sm mb-1`}>
{address.city}, {address.state}
</Text>
<Text style={tw`text-gray-500 text-xs mt-2`}>
Phone: {address.phone}
</Text>
</TouchableOpacity>
))}
</ScrollView>
)}
{/* Pagination Dots */}
{sortedAddresses.length > 1 && (
<View style={tw`flex-row justify-center mt-3`}>
{sortedAddresses.map((_, index: number) => (
<View
key={index}
testID={`address-dot-${index}`}
style={tw`w-2 h-2 rounded-full mx-1 ${
index === currentIndex ? 'bg-brand500' : 'bg-gray-300'
}`}
/>
))}
</View>
)}
{/* Attach Location for selected address - outside the white box */}
{selectedAddress && (() => {
const selectedAddr = sortedAddresses.find(a => a.id === selectedAddress);
return selectedAddr && !selectedAddr.latitude && !selectedAddr.longitude ? (
<>
<MyText style={tw`text-gray-500 text-xs mt-3`}>
No Location is attached to address
</MyText>
<TouchableOpacity
testID="attach-location"
onPress={() => handleAttachLocation(selectedAddr)}
disabled={locationLoading && editingLocationAddressId === selectedAddr.id}
style={tw`mt-2 py-2 px-3 bg-blue-50 rounded-lg self-start`}
>
<Text style={tw`text-blue-600 text-sm font-bold`}>
{locationLoading && editingLocationAddressId === selectedAddr.id ? 'Attaching...' : '+ Attach Current Location'}
</Text>
</TouchableOpacity>
</>
) : null;
})()}
</View>
{/* <BottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}> */}
<RawBottomDialog open={showAddAddress} onClose={() => setShowAddAddress(false)}>
<AddressForm
onResolvedRegion={(info) => {
resolvedRegionRef.current = info;
}}
onSuccess={(addressId) => {
setShowAddAddress(false);
queryClient.invalidateQueries();
if (addressId == null) return;
const resolved = resolvedRegionRef.current;
if (
resolved != null &&
selectedRegionId != null &&
resolved.regionId !== selectedRegionId
) {
const targetRegion = (regions ?? []).find((region) => region.id === resolved.regionId);
if (!targetRegion) {
Alert.alert(
'Unavailable region',
'This address belongs to a region that is not currently available.'
);
return;
}
// The address has been saved; only selecting it is destructive.
confirmSwitch(targetRegion.name, () => {
void (async () => {
await refreshAddresses();
await selectAddress(addressId);
router.replace('/(drawer)/(tabs)/home');
})();
});
return;
}
// Auto-select the newly added address.
void (async () => {
await refreshAddresses();
await selectAddress(addressId);
})();
}}
/>
</RawBottomDialog>
{/* </BottomDialog> */}
</>
);
};
export default CheckoutAddressSelector;