import React, { useCallback, useEffect, useState } from 'react' import { trpc } from '../lib/trpc-client' import { useRegionStore } from '../lib/stores/region-store' import { p, pInput as PInput, MyButton, div } from 'web-components' import { MapPin } from 'lucide-react' import * as Yup from 'yup' import type { AddressFormProps } from '@packages/shared' type Coords = { latitude: number; longitude: number } type ResolvedRegion = { regionId: number; boundId: number | null } // Where the delivery coordinates came from, so the heading can say so. type LocationSource = 'device' | 'map' const validationSchema = Yup.object({ name: Yup.string().required('Name is required'), phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'), addressLine1: Yup.string().required('Address Line 1 is required'), addressLine2: Yup.string(), state: Yup.string().required('State is required'), isDefault: Yup.boolean(), }) export function AddressForm({ onSuccess, initialValues, isEdit = false, onResolvedRegion }: AddressFormProps) { const [isSubmitting, setIsSubmitting] = useState(false) const [submitError, setSubmitError] = useState(null) const [mapOpen, setMapOpen] = useState(false) const [mapCenter, setMapCenter] = useState<{ lat: number; lng: number } | null>(null) const [locating, setLocating] = useState(false) const [locationError, setLocationError] = useState(null) const [locationSource, setLocationSource] = useState( initialValues?.latitude != null && initialValues?.longitude != null ? 'device' : null ) const [currentLocation, setCurrentLocation] = useState( initialValues?.latitude != null && initialValues?.longitude != null ? { latitude: initialValues.latitude, longitude: initialValues.longitude } : null ) const browsingRegionId = useRegionStore((state) => state.selectedRegionId) const browsingRegion = useRegionStore((state) => state.selectedRegion) // The town (region) for this address. Pre-selected from the app's current // browsing region when one exists; otherwise picked from the City dropdown. const [resolvedRegion, setResolvedRegion] = useState(() => browsingRegionId != null ? { regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null } : null ) const utils = trpc.useUtils() // Towns (regions) the user can deliver in — the City field is a picker over them. const { data: regionsData } = trpc.common.listRegions.useQuery() const regions = regionsData ?? [] const cityName = regions.find((region) => region.id === resolvedRegion?.regionId)?.name ?? '' const handleCityChange = useCallback( async (regionId: number) => { if (!currentLocation) { setResolvedRegion({ regionId, boundId: null }) setLocationError('Use your location or pick a point inside this town.') return } setResolvedRegion({ regionId, boundId: null }) setLocationError(null) try { const resolved = await utils.common.resolveBound.fetch({ regionId, lat: currentLocation.latitude, lng: currentLocation.longitude, }) const info: ResolvedRegion = { regionId, boundId: resolved.boundId } setResolvedRegion(info) onResolvedRegion?.(info) } catch { setLocationError('Your location is outside this town. Pick a point on the map inside it.') } }, [utils, currentLocation, onResolvedRegion] ) const [values, setValues] = useState(() => ({ name: initialValues?.name || '', phone: initialValues?.phone || '', addressLine1: initialValues?.addressLine1 || '', addressLine2: initialValues?.addressLine2 || '', city: initialValues?.city || '', state: initialValues?.state || 'Telangana', isDefault: initialValues?.isDefault || false, googleMapsUrl: initialValues?.googleMapsUrl || '', })) const [errors, setErrors] = useState>({}) const resolveLocation = useCallback( async (coords: Coords, source: LocationSource = 'device') => { setCurrentLocation(coords) setLocationSource(source) 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] ) useEffect(() => { if (initialValues?.latitude != null && initialValues?.longitude != null) { void resolveLocation({ latitude: initialValues.latitude, longitude: initialValues.longitude }) } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) // Pre-select the browsing town once known — unless the user already picked a // town or attached a location. useEffect(() => { if (resolvedRegion != null || currentLocation != null) return if (browsingRegionId == null) return setResolvedRegion({ regionId: browsingRegionId, boundId: browsingRegion?.effectiveBoundId ?? null, }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [browsingRegionId, browsingRegion]) // Coordinates picked on the embedded map are delivered via postMessage. useEffect(() => { if (!mapOpen) return const handler = (event: MessageEvent) => { if (event.origin !== window.location.origin) return const data = event.data if ( data?.type === 'location-selected' && typeof data.latitude === 'number' && typeof data.longitude === 'number' ) { setMapOpen(false) void resolveLocation({ latitude: data.latitude, longitude: data.longitude }, 'map') } } window.addEventListener('message', handler) return () => window.removeEventListener('message', handler) }, [mapOpen, resolveLocation]) const createMutation = trpc.user.address.createAddress.useMutation({ onSuccess: (data) => { setIsSubmitting(false) onSuccess(data?.data?.id) }, onError: (error: any) => { setIsSubmitting(false) setSubmitError(error.message || 'Failed to save address') }, }) const updateMutation = trpc.user.address.updateAddress.useMutation({ onSuccess: () => { setIsSubmitting(false) onSuccess() }, onError: (error: any) => { setIsSubmitting(false) setSubmitError(error.message || 'Failed to update address') }, }) const handleChange = (field: string, value: string | boolean) => { setValues((prev) => ({ ...prev, [field]: value })) if (errors[field]) { setErrors((prev) => ({ ...prev, [field]: '' })) } } const handleDetectLocation = () => { if (!navigator.geolocation) { setLocationError('Location is not supported in this browser. Please select on the map.') return } setLocating(true) navigator.geolocation.getCurrentPosition( (position) => { setLocating(false) void resolveLocation({ latitude: position.coords.latitude, longitude: position.coords.longitude, }) }, () => { setLocating(false) setLocationError('Could not get your location. Please select on the map.') }, { enableHighAccuracy: true, timeout: 10000 } ) } const handleSubmit = async () => { try { await validationSchema.validate(values, { abortEarly: false }) if (!currentLocation) { setSubmitError('Please use your current location or select one on the map.') return } if (!resolvedRegion || locationError) { setSubmitError(locationError || 'Please choose a town and a location inside it.') return } setIsSubmitting(true) setSubmitError(null) const payload = { ...values, city: cityName || values.city || '', regionId: resolvedRegion.regionId, latitude: currentLocation.latitude, longitude: currentLocation.longitude, googleMapsUrl: values.googleMapsUrl || undefined, } if (isEdit && initialValues?.id) { updateMutation.mutate({ id: initialValues.id, ...payload }) } else { createMutation.mutate(payload) } } catch (err: any) { const validationErrors: Record = {} err.inner?.forEach((error: any) => { validationErrors[error.path] = error.message }) setErrors(validationErrors) } } return (

{isEdit ? 'Edit Address' : 'Add Address'}

{submitError && (

{submitError}

)}
handleChange('name', e.target.value)} className={errors.name ? 'border-red-500' : ''} /> {errors.name &&

{errors.name}

}
handleChange('phone', e.target.value)} className={errors.phone ? 'border-red-500' : ''} /> {errors.phone &&

{errors.phone}

}
handleChange('addressLine1', e.target.value)} className={errors.addressLine1 ? 'border-red-500' : ''} /> {errors.addressLine1 &&

{errors.addressLine1}

}
handleChange('addressLine2', e.target.value)} />
{/* Location is mandatory: attach the device location or pick on the map. */}

Delivery Location *

{currentLocation ? (

{' '} {locationSource === 'map' ? 'Location Attached from Map' : 'Current Location Attached'}

📍 {currentLocation.latitude.toFixed(5)}, {currentLocation.longitude.toFixed(5)}

) : (
)} {locationError &&

{locationError}

}
{/* Full-screen in-page map picker (same origin, posts coordinates back). */} {mapOpen && (