import { useState, useEffect, useCallback, useRef } from 'react'; import { useJsApiLoader, GoogleMap, Marker, InfoWindow } from '@react-google-maps/api'; import { Loader2, MapPin } from 'lucide-react'; import { PIPELINE } from '../../api/config'; import { dailyReportsClient } from '../../api/clients'; interface StoreLocation { latitude: number; longitude: number; } interface Store { area: string; business_name: string; distance_km: number; location: StoreLocation; route_name: string; store_code: string; } interface NearestStoresResponse { message: string; response: { count: number; stores: Store[]; success: boolean; }; } const mapContainerStyle = { width: '100%', height: '100%', borderRadius: '0px' }; const defaultCenter = { lat: 12.9716, lng: 77.5946 }; export function DailyLogMap({ latitude, longitude, showStoreList = false }: { latitude?: number | string | null; longitude?: number | string | null; showStoreList?: boolean; }) { const [userLocation, setUserLocation] = useState<{ lat: number, lng: number } | null>(null); const [stores, setStores] = useState([]); const [selectedStore, setSelectedStore] = useState(null); const [error, setError] = useState(null); const mapRef = useRef(null); const { isLoaded } = useJsApiLoader({ id: 'google-map-script', googleMapsApiKey: import.meta.env.VITE_GOOGLE_MAPS_API_KEY || '' }); const fetchNearestStores = async (lat: number, lng: number) => { try { const data = await dailyReportsClient.request( 'POST', PIPELINE.endpoints.nearestStores, { latitude: lat, longitude: lng }, { 'accept': 'application/json, text/plain, */*', 'groupid': '25', 'orgid': '57', 'templateid': '189', 'x-pipeline-version': 'draft' } ); if (data.response && data.response.stores) { setStores(data.response.stores); } } catch (err: any) { console.error('An error occurred while fetching stores.', err); } }; useEffect(() => { // If coords provided in props, use them if (latitude && longitude && String(latitude).trim() !== '—' && String(longitude).trim() !== '—') { const lat = Number(latitude); const lng = Number(longitude); if (!isNaN(lat) && !isNaN(lng)) { setUserLocation({ lat, lng }); fetchNearestStores(lat, lng); return; } } // Otherwise fallback to whatever tactic used for mobile if (!navigator.geolocation) { setError('Geolocation is not supported by your browser.'); return; } navigator.geolocation.getCurrentPosition( (position) => { const lat = position.coords.latitude; const lng = position.coords.longitude; setUserLocation({ lat, lng }); fetchNearestStores(lat, lng); }, (err) => { setError(err.message || 'Failed to get location'); }, { enableHighAccuracy: true } ); }, [latitude, longitude]); const onLoad = useCallback(function callback(map: google.maps.Map) { mapRef.current = map; if (userLocation) { const bounds = new window.google.maps.LatLngBounds(); bounds.extend(userLocation); map.fitBounds(bounds); const listener = window.google.maps.event.addListener(map, 'idle', () => { if (map.getZoom()! > 15) { map.setZoom(15); } window.google.maps.event.removeListener(listener); }); } }, [userLocation]); useEffect(() => { if (mapRef.current && userLocation && stores.length > 0) { const bounds = new window.google.maps.LatLngBounds(); bounds.extend(userLocation); stores.forEach(store => { if (store.location) { const lat = Number(store.location.latitude); const lng = Number(store.location.longitude); if (!isNaN(lat) && !isNaN(lng)) { bounds.extend({ lat, lng }); } } }); mapRef.current.fitBounds(bounds); } }, [stores, userLocation]); if (!isLoaded) { return (
); } return (
{error && (
{error}
)}
{/* User's Current Location Marker */} {userLocation && ( )} {/* Stores Markers */} {stores.map((store) => { if (!store.location) return null; const lat = Number(store.location.latitude); const lng = Number(store.location.longitude); if (isNaN(lat) || isNaN(lng)) return null; return ( setSelectedStore(store)} title={store.business_name} /> ); })} {/* Info Window for Selected Store */} {selectedStore && selectedStore.location && !isNaN(Number(selectedStore.location.latitude)) && ( setSelectedStore(null)} >

{selectedStore.business_name}

{selectedStore.area}

{selectedStore.route_name} {selectedStore.distance_km} km
)}
{showStoreList && (

Nearby Stores

{stores.length > 0 ? ( stores.map((store) => (
setSelectedStore(store)}> {store.business_name} {store.store_code} {store.distance_km != null && ( {store.distance_km.toFixed(2)} km away )}
)) ) : ( No nearby stores found. )}
)}
); }