347 lines
13 KiB
TypeScript
347 lines
13 KiB
TypeScript
import React, { useCallback, useEffect, useState } from 'react';
|
||
import { View, Modal, ScrollView, KeyboardAvoidingView, Platform } from 'react-native';
|
||
import { Formik } from 'formik';
|
||
import * as Yup from 'yup';
|
||
import { tw, MyText, MyTouchableOpacity , Checkbox , MyTextInput , LoadingDialog } from 'common-ui';
|
||
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
|
||
import { trpc } from '../trpc-client';
|
||
import LocationAttacher from './LocationAttacher';
|
||
import LocationMapStep from './location/LocationMapStep';
|
||
import type { AddressFormProps } from '@packages/shared';
|
||
import { savePendingAddress } from '@/src/lib/pending-address';
|
||
|
||
type Coords = { latitude: number; longitude: number };
|
||
type ResolvedRegion = { regionId: number; boundId: number | null };
|
||
|
||
const AddressForm: React.FC<AddressFormProps> = ({
|
||
onSuccess,
|
||
initialValues,
|
||
isEdit = false,
|
||
draftMode = false,
|
||
onResolvedRegion,
|
||
}) => {
|
||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||
const [mapOpen, setMapOpen] = useState(false);
|
||
const [currentLocation, setCurrentLocation] = useState<Coords | null>(
|
||
initialValues?.latitude != null && initialValues?.longitude != null
|
||
? { latitude: initialValues.latitude, longitude: initialValues.longitude }
|
||
: null
|
||
);
|
||
// Region is never picked directly: it is derived from the coordinates.
|
||
const [resolvedRegion, setResolvedRegion] = useState<ResolvedRegion | null>(null);
|
||
const [locationError, setLocationError] = useState<string | null>(null);
|
||
|
||
const utils = trpc.useUtils();
|
||
|
||
// Resolve coordinates -> region + bound. Used for whichever source the user
|
||
// picks (attach current location or the map). Out-of-area points are refused.
|
||
const resolveLocation = useCallback(
|
||
async (coords: Coords) => {
|
||
setCurrentLocation(coords);
|
||
setLocationError(null);
|
||
try {
|
||
const resolved = await utils.common.resolveRegionByLocation.fetch({
|
||
lat: coords.latitude,
|
||
lng: coords.longitude,
|
||
});
|
||
if (!resolved) {
|
||
setResolvedRegion(null);
|
||
setLocationError('This location is outside our delivery area. Try selecting on the map.');
|
||
return;
|
||
}
|
||
const info: ResolvedRegion = {
|
||
regionId: resolved.region.id,
|
||
boundId: resolved.bound?.id ?? null,
|
||
};
|
||
setResolvedRegion(info);
|
||
onResolvedRegion?.(info);
|
||
} catch {
|
||
setResolvedRegion(null);
|
||
setLocationError('Could not verify this location. Please try again.');
|
||
}
|
||
},
|
||
[utils, onResolvedRegion]
|
||
);
|
||
|
||
// Resolve any prefilled coordinates once (e.g. edit, or coming from the map).
|
||
useEffect(() => {
|
||
if (initialValues?.latitude != null && initialValues?.longitude != null) {
|
||
void resolveLocation({ latitude: initialValues.latitude, longitude: initialValues.longitude });
|
||
}
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||
}, []);
|
||
|
||
const createAddressMutation = trpc.user.address.createAddress.useMutation({
|
||
onSuccess: (data) => {
|
||
setIsSubmitting(false);
|
||
const addressId = data?.data?.id;
|
||
// Delay to allow modal to close animation
|
||
setTimeout(() => onSuccess(addressId), 350);
|
||
},
|
||
onError: (error: any) => {
|
||
setIsSubmitting(false);
|
||
setSubmitError(error.message || 'Failed to save address');
|
||
},
|
||
});
|
||
|
||
const updateAddressMutation = trpc.user.address.updateAddress.useMutation({
|
||
onSuccess: () => {
|
||
setIsSubmitting(false);
|
||
// Delay to allow modal to close animation
|
||
setTimeout(() => onSuccess(), 350);
|
||
},
|
||
onError: (error: any) => {
|
||
setIsSubmitting(false);
|
||
setSubmitError(error.message || 'Failed to update address');
|
||
},
|
||
});
|
||
|
||
const validationSchema = Yup.object({
|
||
name: Yup.string().required('Name is required'),
|
||
phone: Yup.string().required('Phone is required')
|
||
.matches(/^[6-9]\d{9}$/, 'Phone must be a 10-digit number starting with 6, 7, 8 or 9'),
|
||
addressLine1: Yup.string().required('Address Line 1 is required'),
|
||
addressLine2: Yup.string(),
|
||
city: Yup.string().required('City is required'),
|
||
state: Yup.string().required('State is required'),
|
||
pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
|
||
isDefault: Yup.boolean(),
|
||
});
|
||
|
||
return (
|
||
<KeyboardAvoidingView
|
||
style={tw`flex-1 bg-white`}
|
||
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
|
||
>
|
||
<ScrollView
|
||
style={tw`flex-1`}
|
||
contentContainerStyle={tw`px-4 pt-4 pb-10`}
|
||
keyboardShouldPersistTaps="handled"
|
||
showsVerticalScrollIndicator={false}
|
||
>
|
||
<MyText style={tw`text-xl font-bold mb-4`}>{isEdit ? 'Edit Address' : 'Add Address'}</MyText>
|
||
|
||
{/* Service Area Notice */}
|
||
<View style={tw`bg-amber-50 border border-amber-200 rounded-lg p-3 mb-4`}>
|
||
<View style={tw`flex-row items-center`}>
|
||
<MyText style={tw`text-amber-600 mr-2`}>ℹ️</MyText>
|
||
<MyText style={tw`text-amber-800 text-sm flex-1`}>
|
||
We currently serve only in Mahabubnagar town
|
||
</MyText>
|
||
</View>
|
||
</View>
|
||
|
||
{/* Submit Error Message */}
|
||
{submitError && (
|
||
<View style={tw`bg-red-50 border border-red-200 rounded-lg p-3 mb-4`}>
|
||
<MyText style={tw`text-red-600 text-sm`}>{submitError}</MyText>
|
||
</View>
|
||
)}
|
||
<Formik
|
||
initialValues={initialValues ? { ...initialValues } : {
|
||
name: '',
|
||
phone: '',
|
||
addressLine1: '',
|
||
addressLine2: '',
|
||
city: 'Mahabubnagar',
|
||
state: 'Telangana',
|
||
pincode: '509001',
|
||
isDefault: false,
|
||
googleMapsUrl: '',
|
||
}}
|
||
validationSchema={validationSchema}
|
||
onSubmit={async (values) => {
|
||
if (!currentLocation) {
|
||
setSubmitError('Please attach your current location or select it on the map.');
|
||
return;
|
||
}
|
||
if (!resolvedRegion) {
|
||
setSubmitError(locationError || 'Please choose a location inside our delivery area.');
|
||
return;
|
||
}
|
||
setIsSubmitting(true);
|
||
setSubmitError(null);
|
||
const payload = {
|
||
...values,
|
||
regionId: resolvedRegion.regionId,
|
||
latitude: currentLocation.latitude,
|
||
longitude: currentLocation.longitude,
|
||
googleMapsUrl: values.googleMapsUrl || undefined,
|
||
};
|
||
|
||
if (draftMode && !isEdit) {
|
||
// Signed-out flow: keep the address locally until the user has an
|
||
// account. PendingAddressSync posts it after signup/login.
|
||
await savePendingAddress({
|
||
regionId: resolvedRegion.regionId,
|
||
name: values.name,
|
||
phone: values.phone,
|
||
addressLine1: values.addressLine1,
|
||
addressLine2: values.addressLine2 || undefined,
|
||
city: values.city,
|
||
state: values.state,
|
||
pincode: values.pincode,
|
||
isDefault: values.isDefault,
|
||
latitude: currentLocation.latitude,
|
||
longitude: currentLocation.longitude,
|
||
googleMapsUrl: values.googleMapsUrl || undefined,
|
||
});
|
||
setIsSubmitting(false);
|
||
onSuccess();
|
||
return;
|
||
}
|
||
|
||
if (isEdit && initialValues?.id) {
|
||
updateAddressMutation.mutate({ id: initialValues.id, ...payload });
|
||
} else {
|
||
createAddressMutation.mutate(payload);
|
||
}
|
||
}}
|
||
>
|
||
{({ handleChange, handleBlur, handleSubmit, values, errors, touched, setFieldValue }) => (
|
||
<View style={tw`flex-col gap-2`}>
|
||
<MyTextInput
|
||
testID="address-name"
|
||
placeholder="Name"
|
||
shrunkPadding={true}
|
||
onChangeText={handleChange('name')}
|
||
onBlur={handleBlur('name')}
|
||
value={values.name}
|
||
/>
|
||
{touched.name && errors.name && <MyText style={tw`text-red-500 mb-2`}>{errors.name}</MyText>}
|
||
|
||
<MyTextInput
|
||
testID="address-phone"
|
||
placeholder="Phone"
|
||
shrunkPadding={true}
|
||
keyboardType="phone-pad"
|
||
onChangeText={handleChange('phone')}
|
||
onBlur={handleBlur('phone')}
|
||
value={values.phone}
|
||
/>
|
||
{touched.phone && errors.phone && <MyText style={tw`text-red-500 mb-2`}>{errors.phone}</MyText>}
|
||
|
||
<MyTextInput
|
||
testID="address-line1"
|
||
placeholder="Address Line 1"
|
||
shrunkPadding={true}
|
||
onChangeText={handleChange('addressLine1')}
|
||
onBlur={handleBlur('addressLine1')}
|
||
value={values.addressLine1}
|
||
/>
|
||
{touched.addressLine1 && errors.addressLine1 && <MyText style={tw`text-red-500 mb-2`}>{errors.addressLine1}</MyText>}
|
||
|
||
<MyTextInput
|
||
placeholder="Address Line 2 (Optional)"
|
||
shrunkPadding={true}
|
||
onChangeText={handleChange('addressLine2')}
|
||
onBlur={handleBlur('addressLine2')}
|
||
value={values.addressLine2}
|
||
/>
|
||
|
||
<MyTextInput
|
||
placeholder="City"
|
||
shrunkPadding={true}
|
||
onChangeText={handleChange('city')}
|
||
onBlur={handleBlur('city')}
|
||
value={values.city}
|
||
disabled={true}
|
||
/>
|
||
{touched.city && errors.city && <MyText style={tw`text-red-500 mb-2`}>{errors.city}</MyText>}
|
||
|
||
<MyTextInput
|
||
placeholder="State"
|
||
shrunkPadding={true}
|
||
onChangeText={handleChange('state')}
|
||
onBlur={handleBlur('state')}
|
||
value={values.state}
|
||
disabled={true}
|
||
/>
|
||
{touched.state && errors.state && <MyText style={tw`text-red-500 mb-2`}>{errors.state}</MyText>}
|
||
|
||
<MyTextInput
|
||
placeholder="Pincode"
|
||
shrunkPadding={true}
|
||
keyboardType="numeric"
|
||
onChangeText={handleChange('pincode')}
|
||
onBlur={handleBlur('pincode')}
|
||
value={values.pincode}
|
||
disabled={true}
|
||
/>
|
||
{touched.pincode && errors.pincode && <MyText style={tw`text-red-500 mb-2`}>{errors.pincode}</MyText>}
|
||
|
||
{/* Location is mandatory and drives the region: attach or pick on map. */}
|
||
<View style={tw`mt-1`}>
|
||
<MyText style={tw`text-gray-500 text-xs mb-2`}>Delivery Location *</MyText>
|
||
<LocationAttacher
|
||
initialLocation={currentLocation || undefined}
|
||
showGoogleMapsOption={false}
|
||
onLocationChange={(location) => {
|
||
if (location) void resolveLocation(location);
|
||
}}
|
||
disabled={false}
|
||
/>
|
||
<MyTouchableOpacity
|
||
testID="address-select-from-map"
|
||
onPress={() => setMapOpen(true)}
|
||
style={tw`flex-row items-center mb-1`}
|
||
>
|
||
<MaterialIcons name="map" size={18} color="#3B82F6" />
|
||
<MyText style={tw`text-blue-500 text-sm font-medium ml-1`}>Select on map</MyText>
|
||
</MyTouchableOpacity>
|
||
|
||
{currentLocation && (
|
||
<MyText style={tw`text-gray-500 text-xs mt-1`}>
|
||
📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}
|
||
</MyText>
|
||
)}
|
||
{locationError && (
|
||
<MyText style={tw`text-red-500 text-sm mt-1`}>{locationError}</MyText>
|
||
)}
|
||
</View>
|
||
|
||
<View style={tw`flex-row items-center mb-4 mt-2`}>
|
||
<Checkbox
|
||
checked={values.isDefault}
|
||
onPress={() => setFieldValue('isDefault', !values.isDefault)}
|
||
/>
|
||
<MyText style={tw`ml-2`}>Set as default address</MyText>
|
||
</View>
|
||
|
||
<MyTouchableOpacity
|
||
testID="address-submit"
|
||
style={tw`bg-indigo-600 p-3 rounded ${isSubmitting ? 'opacity-50' : ''}`}
|
||
onPress={() => handleSubmit()}
|
||
disabled={isSubmitting}
|
||
>
|
||
<MyText style={tw`text-white text-center font-bold`}>
|
||
{isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
|
||
</MyText>
|
||
</MyTouchableOpacity>
|
||
<View style={tw`h-8`}></View>
|
||
</View>
|
||
)}
|
||
</Formik>
|
||
|
||
<LoadingDialog
|
||
open={isSubmitting}
|
||
message={isEdit ? "Updating address..." : "Adding address..."}
|
||
/>
|
||
|
||
{/* Full-screen map picker. */}
|
||
<Modal visible={mapOpen} animationType="slide" onRequestClose={() => setMapOpen(false)}>
|
||
<LocationMapStep
|
||
onSelect={(coords) => {
|
||
setMapOpen(false);
|
||
void resolveLocation(coords);
|
||
}}
|
||
onCancel={() => setMapOpen(false)}
|
||
/>
|
||
</Modal>
|
||
</ScrollView>
|
||
</KeyboardAvoidingView>
|
||
);
|
||
};
|
||
|
||
export default AddressForm;
|