freshyo/apps/user-ui/app/(drawer)/(tabs)/me/addresses/index.tsx
2026-10-24 15:19:39 +05:30

337 lines
No EOL
12 KiB
TypeScript

import React, { useEffect, useState } from 'react';
import type { UserAddress } from '@packages/shared'
import { View, Alert, Dimensions, Keyboard } from 'react-native';
import { useRouter } from 'expo-router';
import { AppContainer, MyText, tw, useMarkDataFetchers, MyFlatList, MyTouchableOpacity, BottomDialog, RawBottomDialog } from 'common-ui';
import { trpc } from '@/src/trpc-client';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import AddressForm from '@/src/components/AddressForm';
// Address view — required core of the shared UserAddress + optional geo fields
type Address = Pick<
UserAddress,
'id' | 'regionId' | 'name' | 'phone' | 'addressLine1' | 'addressLine2' | 'city' | 'state' | 'isDefault'
> & {
latitude?: number | null
longitude?: number | null
googleMapsUrl?: string | null
vagueBackfilledCoords?: boolean | null
}
function AddressCard({ address, onEdit, onDelete, onSetDefault, isDeleting }: {
address: Address;
onEdit: (address: Address) => void;
onDelete: (id: number) => void;
onSetDefault: (id: number) => void;
isDeleting?: boolean;
}) {
const formatAddress = (addr: Address) => {
return `${addr.addressLine1}${addr.addressLine2 ? `, ${addr.addressLine2}` : ''}, ${addr.city}, ${addr.state}`;
};
return (
<View
testID={`address-card-${address.id}`}
style={tw`bg-white rounded-lg p-4 mb-3 shadow-sm border border-gray-100`}
>
<View style={tw`flex-row justify-between items-start mb-2`}>
<View style={tw`flex-1`}>
<View style={tw`flex-row items-center mb-1`}>
<MyText weight="semibold" style={tw`text-lg text-gray-800 mr-2`}>
{address.name}
</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-1 rounded-full`}>
<MyText style={tw`text-green-700 text-xs font-medium`}>Default</MyText>
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm mb-1`}>
📞 {address.phone}
</MyText>
<MyText style={tw`text-gray-700 text-sm`}>
📍 {formatAddress(address)}
</MyText>
</View>
</View>
<View style={tw`flex-row justify-end mt-3 space-x-2`}>
{!address.isDefault && (
<MyTouchableOpacity
testID={`address-set-default-${address.id}`}
style={tw`bg-gray-500 px-3 py-2 rounded mr-2`}
onPress={() => onSetDefault(address.id)}
>
<MyText style={tw`text-white text-xs font-medium`}>Set Default</MyText>
</MyTouchableOpacity>
)}
<MyTouchableOpacity
testID={`address-edit-${address.id}`}
style={tw`bg-blue-500 px-3 py-2 rounded mr-2`}
onPress={() => onEdit(address)}
>
<MyText style={tw`text-white text-xs font-medium`}>Edit</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID={`address-delete-${address.id}`}
style={tw`bg-red-500 px-3 py-2 rounded ${isDeleting ? 'opacity-50' : ''}`}
onPress={() => onDelete(address.id)}
disabled={isDeleting}
>
<MyText style={tw`text-white text-xs font-medium`}>
{isDeleting ? 'Deleting...' : 'Delete'}
</MyText>
</MyTouchableOpacity>
</View>
</View>
);
}
export default function Addresses() {
const [modalVisible, setModalVisible] = useState(false);
const [editingAddress, setEditingAddress] = useState<Address | null>(null);
// Reason a delete was refused (only address / still the default / open order) — shown in a bottom sheet.
const [deleteError, setDeleteError] = useState<string | null>(null);
// Size the address sheet to the form when the keyboard is closed; keep the
// full 85% while editing so the scrollable area stays usable.
const [formContentHeight, setFormContentHeight] = useState<number | null>(null);
const [keyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const show = Keyboard.addListener('keyboardDidShow', () => setKeyboardVisible(true));
const hide = Keyboard.addListener('keyboardDidHide', () => setKeyboardVisible(false));
return () => {
show.remove();
hide.remove();
};
}, []);
const windowHeight = Dimensions.get('window').height;
const maxSheetHeight = windowHeight * 0.85;
const sheetHeight = keyboardVisible
? maxSheetHeight
: Math.min(maxSheetHeight, formContentHeight ?? maxSheetHeight);
const { data, isLoading, error, refetch } = trpc.user.address.getUserAddresses.useQuery();
useMarkDataFetchers(() => {
refetch();
});
const addresses = data?.data || [];
const updateAddressMutation = trpc.user.address.updateAddress.useMutation();
const deleteAddressMutation = trpc.user.address.deleteAddress.useMutation();
const utils = trpc.useUtils();
const handleAddAddress = () => {
setEditingAddress(null);
setModalVisible(true);
};
const handleEditAddress = (address: Address) => {
setEditingAddress(address);
setModalVisible(true);
};
const handleDeleteAddress = (id: number) => {
// The server refuses this too, but checking here explains why instead of asking "are you sure?"
// and then failing.
if (addresses.length <= 1) {
setDeleteError('This is your only address. Add another address before deleting this one.');
return;
}
Alert.alert(
'Delete Address',
'Are you sure you want to delete this address?',
[
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: () => {
deleteAddressMutation.mutate({ id }, {
onSuccess: () => {
refetch();
// The quick-delivery selector observes getDefaultAddress.
utils.user.address.getDefaultAddress.invalidate();
Alert.alert('Success', 'Address deleted successfully');
},
onError: (error) => {
setDeleteError(error.message || 'Failed to delete address');
}
});
}
}
]
);
};
const handleSetDefault = (id: number) => {
// Update the address to be default
const addressToUpdate = addresses.find(addr => addr.id === id);
if (addressToUpdate && addressToUpdate.regionId == null) {
Alert.alert('Error', 'This address has no region. Please edit it and choose a region first.');
return;
}
if (addressToUpdate) {
updateAddressMutation.mutate({
id: addressToUpdate.id,
regionId: addressToUpdate.regionId as number,
name: addressToUpdate.name,
phone: addressToUpdate.phone,
addressLine1: addressToUpdate.addressLine1,
addressLine2: addressToUpdate.addressLine2 || undefined,
city: addressToUpdate.city,
state: addressToUpdate.state,
isDefault: true,
// Keep the stored coordinates so the bound is not re-derived from a fallback.
latitude: addressToUpdate.latitude ?? undefined,
longitude: addressToUpdate.longitude ?? undefined,
}, {
onSuccess: () => {
refetch();
utils.user.address.getDefaultAddress.invalidate();
Alert.alert('Success', 'Default address updated');
},
onError: (error) => {
Alert.alert('Error', error.message || 'Failed to update default address');
}
});
}
};
const handleAddressSubmit = () => {
setModalVisible(false);
setEditingAddress(null);
refetch();
};
if (isLoading) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center`}>
<MyText style={tw`text-gray-600`}>Loading addresses...</MyText>
</View>
</AppContainer>
);
}
if (error) {
return (
<AppContainer>
<View style={tw`flex-1 justify-center items-center p-4`}>
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
<MyText style={tw`text-red-600 text-center mt-2 mb-4`}>
Failed to load addresses. Please try again.
</MyText>
<MyTouchableOpacity
testID="addresses-retry-button"
style={tw`bg-blue-500 px-4 py-2 rounded`}
onPress={() => refetch()}
>
<MyText style={tw`text-white font-medium`}>Retry</MyText>
</MyTouchableOpacity>
</View>
</AppContainer>
);
}
return (
<>
<MyFlatList
data={addresses}
renderItem={({ item }) => (
<AddressCard
address={item}
onEdit={handleEditAddress}
onDelete={handleDeleteAddress}
onSetDefault={handleSetDefault}
/>
)}
keyExtractor={(item) => item.id.toString()}
ListHeaderComponent={() => (
<View style={tw`flex-row justify-between items-center p-4 pb-2`}>
<MyText weight="bold" style={tw`text-2xl text-gray-800`}>
My Addresses
</MyText>
<MyTouchableOpacity
testID="addresses-add-button"
style={tw`bg-blue-500 p-2 rounded-full`}
onPress={handleAddAddress}
>
<MaterialIcons name="add" size={24} color="white" />
</MyTouchableOpacity>
</View>
)}
ListEmptyComponent={() => (
<View style={tw`justify-center items-center py-12`}>
<MaterialIcons name="location-off" size={64} color="#9CA3AF" />
<MyText style={tw`text-gray-500 text-center mt-4 mb-2`}>
No addresses found
</MyText>
<MyText style={tw`text-gray-400 text-center mb-6`}>
Add your first delivery address
</MyText>
<MyTouchableOpacity
testID="addresses-empty-add-button"
style={tw`bg-blue-500 px-6 py-3 rounded-lg`}
onPress={handleAddAddress}
>
<MyText style={tw`text-white font-medium`}>Add Address</MyText>
</MyTouchableOpacity>
</View>
)}
contentContainerStyle={tw`p-4`}
showsVerticalScrollIndicator={false}
/>
<RawBottomDialog open={modalVisible} onClose={() => setModalVisible(false)}>
<View style={[tw`bg-white rounded-t-2xl`, { height: sheetHeight }]}>
<AddressForm
onContentHeightChange={setFormContentHeight}
onSuccess={handleAddressSubmit}
initialValues={editingAddress ? {
id: editingAddress.id,
regionId: editingAddress.regionId ?? undefined,
name: editingAddress.name,
phone: editingAddress.phone,
addressLine1: editingAddress.addressLine1,
addressLine2: editingAddress.addressLine2 || '',
city: editingAddress.city,
state: editingAddress.state,
isDefault: editingAddress.isDefault,
// Preserve the saved location. Migration-backfilled placeholder
// coordinates are the only ones we withhold, so the user has to
// pick a real point instead of editing around a fake one.
latitude: editingAddress.vagueBackfilledCoords
? undefined
: (editingAddress.latitude ?? undefined),
longitude: editingAddress.vagueBackfilledCoords
? undefined
: (editingAddress.longitude ?? undefined),
googleMapsUrl: editingAddress.googleMapsUrl ?? undefined,
} : undefined}
isEdit={!!editingAddress}
/>
</View>
</RawBottomDialog>
<BottomDialog open={deleteError !== null} onClose={() => setDeleteError(null)}>
<View style={tw`pb-6`}>
<View style={tw`flex-row items-center mb-2`}>
<MaterialIcons name="error-outline" size={22} color="#dc2626" />
<MyText style={tw`text-lg font-bold text-slate-900 ml-2`}>Cannot delete address</MyText>
</View>
<MyText style={tw`text-sm text-slate-600 mb-5`}>{deleteError}</MyText>
<MyTouchableOpacity
testID="address-delete-error-ok"
onPress={() => setDeleteError(null)}
style={tw`bg-brand500 py-3.5 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>OK</MyText>
</MyTouchableOpacity>
</View>
</BottomDialog>
</>
);
}