import React, { useState, useEffect, useRef } from 'react' import { motion } from 'framer-motion' import { FaTimes, FaSearch, FaMapMarkerAlt } from 'react-icons/fa' import classNames from 'classnames' import { Location } from '@/types/intranet' interface LocationPickerProps { onSelect: (location: Location) => void onClose: () => void } // Google Maps API key - .env dosyasından alınmalı const GOOGLE_API_KEY = import.meta.env.VITE_GOOGLE_MAPS_API_KEY || '' declare global { interface Window { google: any initGoogleMaps?: () => void } } const LocationPicker: React.FC = ({ onSelect, onClose }) => { const [searchQuery, setSearchQuery] = useState('') const [locations, setLocations] = useState([]) const [selectedLocation, setSelectedLocation] = useState(null) const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) const [isGoogleLoaded, setIsGoogleLoaded] = useState(false) const searchInputRef = useRef(null) const autocompleteServiceRef = useRef(null) const placesServiceRef = useRef(null) const debounceTimerRef = useRef() const scriptLoadedRef = useRef(false) // Google Maps SDK'yı yükle useEffect(() => { if (scriptLoadedRef.current) return const loadGoogleMaps = () => { if (window.google && window.google.maps && window.google.maps.places) { setIsGoogleLoaded(true) autocompleteServiceRef.current = new window.google.maps.places.AutocompleteService() const mapDiv = document.createElement('div') const map = new window.google.maps.Map(mapDiv) placesServiceRef.current = new window.google.maps.places.PlacesService(map) return } if (!GOOGLE_API_KEY) { setError('Google Maps API anahtarı bulunamadı. Lütfen .env dosyasına VITE_GOOGLE_MAPS_API_KEY ekleyin.') return } // Script zaten yüklendiyse sadece bekle const existingScript = document.querySelector('script[src*="maps.googleapis.com"]') if (existingScript) { const checkInterval = setInterval(() => { if (window.google && window.google.maps && window.google.maps.places) { clearInterval(checkInterval) setIsGoogleLoaded(true) autocompleteServiceRef.current = new window.google.maps.places.AutocompleteService() const mapDiv = document.createElement('div') const map = new window.google.maps.Map(mapDiv) placesServiceRef.current = new window.google.maps.places.PlacesService(map) } }, 100) return } // Yeni script ekle const script = document.createElement('script') script.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&libraries=places&language=tr` script.async = true script.defer = true script.onload = () => { if (window.google && window.google.maps && window.google.maps.places) { setIsGoogleLoaded(true) autocompleteServiceRef.current = new window.google.maps.places.AutocompleteService() const mapDiv = document.createElement('div') const map = new window.google.maps.Map(mapDiv) placesServiceRef.current = new window.google.maps.places.PlacesService(map) } } script.onerror = () => { setError('Google Maps yüklenemedi. Lütfen internet bağlantınızı kontrol edin.') } document.head.appendChild(script) scriptLoadedRef.current = true } loadGoogleMaps() }, []) useEffect(() => { searchInputRef.current?.focus() }, []) // Google Places Autocomplete ile konum arama useEffect(() => { if (debounceTimerRef.current) { clearTimeout(debounceTimerRef.current) } if (searchQuery.trim() === '') { setLocations([]) setError(null) return } if (!isGoogleLoaded) { return } debounceTimerRef.current = setTimeout(async () => { setIsLoading(true) setError(null) try { // Google Places Autocomplete Service kullan (CORS yok) autocompleteServiceRef.current.getPlacePredictions( { input: searchQuery, componentRestrictions: { country: 'tr' }, language: 'tr' }, async (predictions: any, status: any) => { if (status === window.google.maps.places.PlacesServiceStatus.ZERO_RESULTS) { setLocations([]) setIsLoading(false) return } if (status !== window.google.maps.places.PlacesServiceStatus.OK) { setError('Konum arama başarısız') setIsLoading(false) return } if (!predictions || predictions.length === 0) { setLocations([]) setIsLoading(false) return } // Her bir prediction için detaylı bilgi al const detailedLocations: Location[] = [] let completed = 0 predictions.forEach((prediction: any) => { placesServiceRef.current.getDetails( { placeId: prediction.place_id, fields: ['name', 'formatted_address', 'geometry', 'place_id'] }, (place: any, placeStatus: any) => { completed++ if (placeStatus === window.google.maps.places.PlacesServiceStatus.OK && place) { detailedLocations.push({ id: place.place_id, name: place.name, address: place.formatted_address, lat: place.geometry.location.lat(), lng: place.geometry.location.lng(), placeId: place.place_id }) } // Tüm istekler tamamlandıysa state'i güncelle if (completed === predictions.length) { setLocations(detailedLocations) setIsLoading(false) } } ) }) } ) } catch (err) { console.error('Location search error:', err) setError('Konum arama sırasında bir hata oluştu') setIsLoading(false) } }, 500) // 500ms debounce return () => { if (debounceTimerRef.current) { clearTimeout(debounceTimerRef.current) } } }, [searchQuery, isGoogleLoaded]) const handleSelect = (location: Location) => { setSelectedLocation(location) } const handleConfirm = () => { if (selectedLocation) { onSelect(selectedLocation) onClose() } } return (
{/* Header */}

Konum Ekle

{/* Search */}
setSearchQuery(e.target.value)} placeholder="Konum ara..." disabled={!isGoogleLoaded} className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-600 disabled:cursor-not-allowed" />
{!isGoogleLoaded && (

Google Maps yükleniyor...

)}
{/* Location List */}
{!isGoogleLoaded ? (

Google Maps yükleniyor...

) : isLoading ? (

Konumlar aranıyor...

) : error ? (

{error}

) : searchQuery.trim() === '' ? (

Aramak istediğiniz konumu yazın

Örn: Taksim, İstanbul

) : locations.length === 0 ? (

Konum bulunamadı. Farklı bir arama yapın.

) : (
{locations.map((location) => ( ))}
)}
{/* Footer */}
{selectedLocation ? ( {selectedLocation.name} ) : ( Bir konum seçin )}
) } export default LocationPicker