
'use client';

/// <reference types="../types/google-maps" />

import { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { MapPin, Search } from 'lucide-react';

interface LocationPickerProps {
  onLocationSelect: (lat: number, lng: number, address: string) => void;
  initialCenter?: { lat: number; lng: number };
}

export function LocationPicker({ onLocationSelect, initialCenter }: LocationPickerProps) {
  const [map, setMap] = useState<any | null>(null);
  const [marker, setMarker] = useState<any | null>(null);
  const [selectedLocation, setSelectedLocation] = useState<{
    lat: number;
    lng: number;
    address: string;
  } | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const mapRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!mapRef.current) return;

    const initMap = () => {
      const center = initialCenter || { lat: -26.2041, lng: 28.0473 };
      
      const googleMap = new (window as any).google.maps.Map(mapRef.current!, {
        center,
        zoom: 12,
        mapTypeControl: false,
        fullscreenControl: false,
        streetViewControl: false,
      });

      const mapMarker = new (window as any).google.maps.Marker({
        map: googleMap,
        position: center,
        draggable: true,
      });

      // Get initial address
      const geocoder = new (window as any).google.maps.Geocoder();
      geocoder.geocode({ location: center }, (results: any, status: any) => {
        if (status === 'OK' && results?.[0]) {
          setSelectedLocation({
            lat: center.lat,
            lng: center.lng,
            address: results[0].formatted_address,
          });
        }
      });

      // Handle marker drag
      mapMarker.addListener('dragend', () => {
        const position = mapMarker.getPosition();
        if (position) {
          const lat = position.lat();
          const lng = position.lng();
          
          geocoder.geocode({ location: { lat, lng } }, (results: any, status: any) => {
            if (status === 'OK' && results?.[0]) {
              setSelectedLocation({
                lat,
                lng,
                address: results[0].formatted_address,
              });
            }
          });
        }
      });

      // Handle map click
      googleMap.addListener('click', (e: any) => {
        const lat = e.latLng?.lat();
        const lng = e.latLng?.lng();
        
        if (lat && lng) {
          mapMarker.setPosition({ lat, lng });
          
          geocoder.geocode({ location: { lat, lng } }, (results: any, status: any) => {
            if (status === 'OK' && results?.[0]) {
              setSelectedLocation({
                lat,
                lng,
                address: results[0].formatted_address,
              });
            }
          });
        }
      });

      // Setup autocomplete
      if (searchInputRef.current) {
        const autocomplete = new (window as any).google.maps.places.Autocomplete(searchInputRef.current, {
          fields: ['geometry', 'formatted_address'],
          componentRestrictions: { country: 'za' }, // South Africa
        });

        autocomplete.addListener('place_changed', () => {
          const place = autocomplete.getPlace();
          if (place.geometry?.location) {
            const lat = place.geometry.location.lat();
            const lng = place.geometry.location.lng();
            
            googleMap.setCenter({ lat, lng });
            mapMarker.setPosition({ lat, lng });
            
            setSelectedLocation({
              lat,
              lng,
              address: place.formatted_address || '',
            });
          }
        });
      }

      setMap(googleMap);
      setMarker(mapMarker);
    };

    if (typeof (window as any).google !== 'undefined') {
      initMap();
    } else {
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || 'YOUR_API_KEY'}&libraries=places`;
      script.async = true;
      script.defer = true;
      script.onload = initMap;
      document.head.appendChild(script);
    }
  }, [initialCenter]);

  const handleConfirm = () => {
    if (selectedLocation) {
      onLocationSelect(
        selectedLocation.lat,
        selectedLocation.lng,
        selectedLocation.address
      );
    }
  };

  const handleUseCurrentLocation = () => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const lat = position.coords.latitude;
          const lng = position.coords.longitude;
          
          if (map && marker) {
            map.setCenter({ lat, lng });
            marker.setPosition({ lat, lng });
            
            const geocoder = new (window as any).google.maps.Geocoder();
            geocoder.geocode({ location: { lat, lng } }, (results: any, status: any) => {
              if (status === 'OK' && results?.[0]) {
                setSelectedLocation({
                  lat,
                  lng,
                  address: results[0].formatted_address,
                });
              }
            });
          }
        },
        (error) => {
          console.error('Error getting location:', error);
        }
      );
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <Input
            ref={searchInputRef}
            type="text"
            placeholder="Search for an address..."
            className="pl-10"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <Button
          type="button"
          variant="outline"
          onClick={handleUseCurrentLocation}
          className="flex-shrink-0"
        >
          <MapPin className="mr-2 w-4 h-4" />
          Use My Location
        </Button>
      </div>

      <div ref={mapRef} className="w-full h-[400px] rounded-lg border" />

      {selectedLocation && (
        <div className="space-y-3">
          <div className="p-3 bg-gray-50 rounded-lg">
            <p className="text-sm text-gray-600 mb-1">Selected Location:</p>
            <p className="font-medium text-brand-dark-blue">{selectedLocation.address}</p>
            <p className="text-xs text-gray-500 mt-1">
              Lat: {selectedLocation.lat.toFixed(6)}, Lng: {selectedLocation.lng.toFixed(6)}
            </p>
          </div>
          
          <Button
            type="button"
            onClick={handleConfirm}
            className="w-full bg-brand-green hover:bg-brand-green/90"
          >
            Confirm Location
          </Button>
        </div>
      )}
    </div>
  );
}
