freshyo/apps/user-ui/src/components/location/LocationFallbackFlow.tsx
2026-10-18 21:51:01 +05:30

367 lines
14 KiB
TypeScript

import React, { useCallback, useEffect, useRef, useState } from 'react'
import { View, ScrollView, ActivityIndicator } from 'react-native'
import { useQueryClient } from '@tanstack/react-query'
import MaterialIcons from '@expo/vector-icons/MaterialIcons'
import { MyText, MyTouchableOpacity, tw, theme } from 'common-ui'
import { trpc } from '@/src/trpc-client'
import { useAuthOptional } from '@/src/contexts/AuthContext'
import { useAddressStore } from '@/src/store/addressStore'
import { confirmRegionSwitch } from '@/src/lib/region-switch'
import AddressForm from '@/src/components/AddressForm'
import Login from '@/app/(auth)/login'
type ResolvedRegion = { regionId: number; boundId: number | null }
/** Address fields the chooser needs (serialized API shape). */
interface ChooserAddress {
id: number
regionId: number | null
boundId: number | null
latitude: number | null
longitude: number | null
name: string
phone: string
addressLine1: string
addressLine2: string | null
city: string
state: string
isDefault: boolean
}
interface LocationFallbackFlowProps {
/** Present when hosted in a sheet; lets the caller dismiss after a choice. */
onClose?: () => void
/**
* Why the location couldn't be used (permission not granted / turned off /
* couldn't get a fix). Shown above the address options.
*/
notice?: string
/**
* When set, the notice also shows a button that deep-links to the OS location
* settings (used when the OS state can't be fixed from inside the app).
*/
onOpenSettings?: () => void
/**
* Whether to mark the address the app would fall back to (the user's default) as
* the active one. The startup gate passes false: no region exists yet, so nothing
* is chosen, and a pre-marked card reads as "already done" instead of "tap this".
*/
highlightActiveAddress?: boolean
}
/**
* Region is no longer chosen directly. The user either picks a saved address
* (which switches the browsing region + bound and clears the cart) or adds a
* new one (coordinates required, via attach-location or the map).
*/
const LocationFallbackFlow: React.FC<LocationFallbackFlowProps> = ({
onClose,
notice,
onOpenSettings,
highlightActiveAddress = true,
}) => {
const queryClient = useQueryClient()
const utils = trpc.useUtils()
const auth = useAuthOptional()
const isAuthenticated = auth?.isAuthenticated ?? false
const setSelectedAddressId = useAddressStore((state) => state.setSelectedAddressId)
const selectedAddressId = useAddressStore((state) => state.selectedAddressId)
const [mode, setMode] = useState<'choose' | 'add' | 'login'>('choose')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState<string | null>(null)
const resolvedRef = useRef<ResolvedRegion | null>(null)
// The gate renders outside the root navigator (see LocationTestWrapper), so we
// cannot router.push to /login here — render the login screen in place. Once
// auth lands, return to the address chooser with the saved addresses loaded.
useEffect(() => {
if (isAuthenticated && mode === 'login') setMode('choose')
}, [isAuthenticated, mode])
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated,
})
const updateAddress = trpc.user.address.updateAddress.useMutation()
const addresses = (addressesQuery.data?.data ?? []) as unknown as ChooserAddress[]
// The address the app treats as active: an explicit pick (bar / cart / this
// sheet) wins, otherwise the default. Same precedence as LocationBar,
// CheckoutAddressSelector and CheckoutAddressDisplay, so the sheet cannot
// disagree with the bar it was opened from. Null in the startup gate, where
// nothing has been chosen yet — see highlightActiveAddress.
const activeAddressId = highlightActiveAddress
? selectedAddressId ?? addresses.find((address) => address.isDefault)?.id ?? null
: null
const activate = useCallback(
async (regionId: number, boundId: number | null): Promise<boolean> => {
setBusy(true)
try {
const regions = await utils.common.listRegions.fetch()
const region = regions.find((candidate) => candidate.id === regionId)
if (!region) {
setMessage('This location is no longer serviceable.')
return false
}
await confirmRegionSwitch(region, queryClient, boundId)
return true
} finally {
setBusy(false)
}
},
[queryClient, utils]
)
const handleSelect = useCallback(
async (address: ChooserAddress) => {
if (address.regionId == null) {
setMessage('This saved address has no region. Please add a new address instead.')
return
}
let boundId = address.boundId
if (boundId == null && address.latitude != null && address.longitude != null) {
try {
const resolved = await utils.common.resolveRegionByLocation.fetch({
lat: address.latitude,
lng: address.longitude,
})
boundId = resolved?.bound?.id ?? null
} catch {
boundId = null
}
}
const switched = await activate(address.regionId, boundId)
// Record the pick AFTER the switch: confirmRegionSwitch clears the
// selection, so setting it before would be wiped.
if (switched) {
setSelectedAddressId(address.id)
}
onClose?.()
},
[activate, onClose, setSelectedAddressId, utils]
)
const handleSetDefault = useCallback(
(address: ChooserAddress) => {
if (address.regionId == null) {
setMessage('This saved address has no region. Please add a new address instead.')
return
}
updateAddress.mutate(
{
id: address.id,
regionId: address.regionId,
name: address.name,
phone: address.phone,
addressLine1: address.addressLine1,
addressLine2: address.addressLine2 || undefined,
city: address.city,
state: address.state,
isDefault: true,
latitude: address.latitude ?? undefined,
longitude: address.longitude ?? undefined,
},
{
onSuccess: () => {
void utils.user.address.getUserAddresses.invalidate()
void utils.user.address.getDefaultAddress.invalidate()
},
onError: (error: any) => setMessage(error?.message || 'Could not set default address.'),
}
)
},
[updateAddress, utils]
)
const handleFormSuccess = useCallback(
async (addressId?: number) => {
const resolved = resolvedRef.current
const switched = resolved ? await activate(resolved.regionId, resolved.boundId) : true
// Same ordering rule as handleSelect. No id while signed out (the draft is
// posted later by PendingAddressSync), so only select when we have one.
if (switched && addressId != null) {
setSelectedAddressId(addressId)
}
onClose?.()
},
[activate, onClose, setSelectedAddressId]
)
if (mode === 'login') {
return (
<View style={tw`flex-1 bg-white`}>
<Login />
<MyTouchableOpacity
testID="location-login-back"
onPress={() => setMode('choose')}
activeOpacity={0.7}
style={tw`absolute left-4 top-14 w-10 h-10 rounded-full bg-white/90 items-center justify-center shadow`}
>
<MaterialIcons name="arrow-back" size={22} color="#374151" />
</MyTouchableOpacity>
</View>
)
}
if (mode === 'add') {
return (
<View style={tw`flex-1 bg-white`}>
<MyTouchableOpacity
testID="location-add-back"
onPress={() => setMode('choose')}
style={tw`px-5 pt-12 pb-2 flex-row items-center`}
>
<MaterialIcons name="arrow-back" size={22} color="#4B5563" />
<MyText style={tw`text-gray-600 ml-1`}>Back</MyText>
</MyTouchableOpacity>
<AddressForm
draftMode={!isAuthenticated}
onResolvedRegion={(info) => {
resolvedRef.current = info
}}
onSuccess={handleFormSuccess}
/>
</View>
)
}
return (
<View style={tw`flex-1 bg-white`}>
<View style={tw`px-6 pt-12 pb-4 flex-row items-start justify-between`}>
<View style={tw`flex-1`}>
<MyText style={tw`text-3xl font-extrabold text-gray-900`}>Delivery Address</MyText>
<MyText style={tw`text-gray-500 mt-2`}>
Choose a saved address, or add a new one. Your region follows the address.
</MyText>
</View>
{onClose && (
<MyTouchableOpacity onPress={onClose} style={tw`p-1`}>
<MaterialIcons name="close" size={24} color="#9CA3AF" />
</MyTouchableOpacity>
)}
</View>
{notice && (
<View style={tw`mx-5 mb-3 bg-amber-50 border border-amber-200 rounded-xl p-3`}>
<View style={tw`flex-row`}>
<MaterialIcons name="location-off" size={18} color="#B45309" style={tw`mr-2`} />
<MyText style={tw`text-amber-800 text-sm flex-1`}>{notice}</MyText>
</View>
{onOpenSettings && (
<MyTouchableOpacity
testID="open-location-settings"
onPress={onOpenSettings}
activeOpacity={0.85}
style={tw`mt-3 bg-amber-600 px-4 py-2 rounded-lg self-start`}
>
<MyText style={tw`text-white font-bold text-sm`}>Open location settings</MyText>
</MyTouchableOpacity>
)}
</View>
)}
{message && (
<View style={tw`mx-5 mb-2 bg-red-50 border border-red-200 rounded-xl p-3`}>
<MyText style={tw`text-red-600 text-sm`}>{message}</MyText>
</View>
)}
{/* The list owns the remaining height, so it scrolls while the footer below
stays pinned (and is therefore always reachable). */}
<View style={tw`flex-1`}>
<ScrollView style={tw`flex-1`} contentContainerStyle={tw`px-5 pb-10`}>
{isAuthenticated && addressesQuery.isLoading && (
<View style={tw`items-center justify-center py-10`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
)}
{isAuthenticated &&
addresses.map((address) => {
const isActive = address.id === activeAddressId
return (
<View
key={address.id}
style={tw`border rounded-2xl p-4 mb-3 shadow-sm ${isActive ? 'bg-brand50 border-brand500' : 'bg-white border-gray-100'
}`}
>
<MyTouchableOpacity testID={`location-address-${address.id}`} disabled={busy} onPress={() => handleSelect(address)}>
<View style={tw`flex-row items-center mb-1`}>
<MyText style={tw`text-base font-bold text-gray-900 mr-2`}>{address.name}</MyText>
{address.isDefault && (
<View style={tw`bg-green-100 px-2 py-0.5 rounded-full`}>
<MyText style={tw`text-green-700 text-[10px] font-semibold`}>Default</MyText>
</View>
)}
{isActive && (
<View testID="location-address-active" style={tw`ml-auto bg-brand500 w-5 h-5 rounded-full items-center justify-center`}>
<MaterialIcons name="check" size={14} color="white" />
</View>
)}
</View>
<MyText style={tw`text-gray-600 text-sm`}>
{address.addressLine1}
{address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city}
</MyText>
</MyTouchableOpacity>
{!address.isDefault && (
<MyTouchableOpacity
onPress={() => handleSetDefault(address)}
disabled={busy || updateAddress.isPending}
style={tw`mt-2 self-start`}
>
<MyText style={tw`text-blue-500 text-xs font-medium`}>Set as default</MyText>
</MyTouchableOpacity>
)}
</View>
)
})}
{isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && (
<MyText style={tw`text-gray-500 mb-3`}>No saved addresses yet.</MyText>
)}
<MyTouchableOpacity
testID="location-add-address"
onPress={() => setMode('add')}
style={tw`bg-white border border-dashed border-gray-300 rounded-2xl p-4 flex-row items-center`}
>
<MaterialIcons name="add-location-alt" size={22} color={theme.colors.brand500} />
<MyText style={tw`text-gray-900 font-bold ml-2`}>Add a new address</MyText>
</MyTouchableOpacity>
</ScrollView>
</View>
{/* Pinned footer: shown for the whole signed-out time, not only once auth
has settled, so the Login button is always available. */}
{!isAuthenticated && (
<View style={tw`px-5 pt-3 pb-6 border-t border-gray-100 bg-white`}>
<MyText style={tw`text-gray-500 text-sm text-center mb-3`}>
Login to get existing addresses.
</MyText>
<MyTouchableOpacity
testID="location-login"
onPress={() => setMode('login')}
activeOpacity={0.85}
style={tw`bg-brand500 py-3 rounded-xl items-center`}
>
<MyText style={tw`text-white font-bold`}>Login</MyText>
</MyTouchableOpacity>
</View>
)}
{busy && (
<View testID="location-busy-overlay" style={tw`absolute inset-0 bg-black/20 items-center justify-center`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
</View>
)}
</View>
)
}
export default LocationFallbackFlow