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 = ({ 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(null) const resolvedRef = useRef(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 => { 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 ( 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`} > ) } if (mode === 'add') { return ( setMode('choose')} style={tw`px-5 pt-12 pb-2 flex-row items-center`} > Back { resolvedRef.current = info }} onSuccess={handleFormSuccess} /> ) } return ( Delivery Address Choose a saved address, or add a new one. Your region follows the address. {onClose && ( )} {notice && ( {notice} {onOpenSettings && ( Open location settings )} )} {message && ( {message} )} {/* The list owns the remaining height, so it scrolls while the footer below stays pinned (and is therefore always reachable). */} {isAuthenticated && addressesQuery.isLoading && ( )} {isAuthenticated && addresses.map((address) => { const isActive = address.id === activeAddressId return ( handleSelect(address)}> {address.name} {address.isDefault && ( Default )} {isActive && ( )} {address.addressLine1} {address.addressLine2 ? `, ${address.addressLine2}` : ''}, {address.city} {!address.isDefault && ( handleSetDefault(address)} disabled={busy || updateAddress.isPending} style={tw`mt-2 self-start`} > Set as default )} ) })} {isAuthenticated && !addressesQuery.isLoading && addresses.length === 0 && ( No saved addresses yet. )} setMode('add')} style={tw`bg-white border border-dashed border-gray-300 rounded-2xl p-4 flex-row items-center`} > Add a new address {/* Pinned footer: shown for the whole signed-out time, not only once auth has settled, so the Login button is always available. */} {!isAuthenticated && ( Login to get existing addresses. setMode('login')} activeOpacity={0.85} style={tw`bg-brand500 py-3 rounded-xl items-center`} > Login )} {busy && ( )} ) } export default LocationFallbackFlow