// src/components/GooglePlacesAutocomplete.tsx
'use client';

import React, { useEffect, useRef, useState } from 'react';
import { Autocomplete, TextField, FormControl, InputLabel, FormHelperText } from '@mui/material';

interface GooglePlacesAutocompleteProps {
  value: string;
  onChange: (value: string) => void;
  onPlaceSelect: (place: any) => void;
  error?: boolean;
  helperText?: string;
  label?: string;
  placeholder?: string;
}

declare global {
  interface Window {
    google: any;
    initGooglePlaces: () => void;
  }
}

const GooglePlacesAutocomplete: React.FC<GooglePlacesAutocompleteProps> = ({
  value,
  onChange,
  onPlaceSelect,
  error = false,
  helperText,
  label = '',
  placeholder = ''
}) => {
  const [suggestions, setSuggestions] = useState<any[]>([]);
  const [isLoaded, setIsLoaded] = useState(false);
  const autocompleteService = useRef<any>(null);
  const placesService = useRef<any>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Initialize Google Places API
  useEffect(() => {
    const initializeGooglePlaces = () => {
      console.log('Initializing Google Places...'); // Debug log
      console.log('Google API Key:', process.env.NEXT_PUBLIC_GOOGLE_API_KEY); // Debug log
      
      if (window.google && window.google.maps && window.google.maps.places) {
        console.log('Google Maps and Places loaded successfully'); // Debug log
        autocompleteService.current = new window.google.maps.places.AutocompleteService();
        
        // Create a hidden div for PlacesService
        const mapDiv = document.createElement('div');
        mapDiv.style.display = 'none';
        document.body.appendChild(mapDiv);
        
        const map = new window.google.maps.Map(mapDiv);
        placesService.current = new window.google.maps.places.PlacesService(map);
        
        setIsLoaded(true);
        console.log('Google Places services initialized'); // Debug log
      } else {
        console.error('Google Maps or Places not available'); // Debug log
      }
    };

    // Check if Google Maps is already loaded
    if (window.google && window.google.maps) {
      initializeGooglePlaces();
    } else {
      console.log('Loading Google Maps script...'); // Debug log
      // Load Google Maps script if not already loaded
      const apiKey = process.env.NEXT_PUBLIC_GOOGLE_API_KEY || 'AIzaSyA4di-tXOemm0DYPBD99AcVxT-DoekbPbA';
      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`;
      script.async = true;
      script.defer = true;
      script.onload = initializeGooglePlaces;
      script.onerror = () => {
        console.error('Failed to load Google Maps script'); // Debug log
      };
      document.head.appendChild(script);
    }
  }, []);

  const handleInputChange = (inputValue: string) => {
    onChange(inputValue);

    if (inputValue.length > 2 && autocompleteService.current && isLoaded) {
      console.log('Searching for:', inputValue); // Debug log
      console.log('AutocompleteService available:', !!autocompleteService.current); // Debug log
      
      autocompleteService.current.getPlacePredictions(
        {
          input: inputValue,
          types: ['address'],
          // Remove country restrictions to allow global search
        },
        (predictions: any[] | null, status: any) => {
          console.log('Google Places Status:', status); // Debug log
          console.log('Predictions:', predictions); // Debug log
          if (status === window.google.maps.places.PlacesServiceStatus.OK && predictions) {
            setSuggestions(predictions);
          } else {
            console.log('No predictions or error:', status); // Debug log
            setSuggestions([]);
          }
        }
      );
    } else {
      if (inputValue.length <= 2) {
        console.log('Input too short:', inputValue.length); // Debug log
      }
      if (!autocompleteService.current) {
        console.log('AutocompleteService not available'); // Debug log
      }
      if (!isLoaded) {
        console.log('Google Places not loaded yet'); // Debug log
      }
      setSuggestions([]);
    }
  };

  const handlePlaceSelect = (placeId: string) => {
    if (placesService.current) {
      placesService.current.getDetails(
        {
          placeId: placeId,
          fields: ['formatted_address', 'geometry', 'address_components', 'name']
        },
        (place: any | null, status: any) => {
          if (status === window.google.maps.places.PlacesServiceStatus.OK && place) {
            onChange(place.formatted_address || '');
            onPlaceSelect(place);
            setSuggestions([]);
          }
        }
      );
    }
  };

  return (
    <FormControl error={error} fullWidth>
      <InputLabel>{label}</InputLabel>
      {!isLoaded && (
        <div style={{ 
          padding: '8px 12px', 
          fontSize: '0.875rem', 
          color: '#666',
          border: '1px solid #ddd',
          borderRadius: '4px',
          backgroundColor: '#f5f5f5'
        }}>
          Loading Google Places API...
        </div>
      )}
      {isLoaded && (
        <Autocomplete
        freeSolo
        options={suggestions}
        getOptionLabel={(option) => 
          typeof option === 'string' ? option : option.description
        }
        value={value}
        onInputChange={(event, newInputValue) => {
          handleInputChange(newInputValue);
        }}
        onChange={(event, newValue) => {
          if (newValue && typeof newValue === 'object' && newValue.place_id) {
            handlePlaceSelect(newValue.place_id);
          }
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            ref={inputRef}
            label={label}
            placeholder={placeholder}
            error={error}
            helperText={helperText}
            variant="outlined"
            fullWidth
          />
        )}
        renderOption={(props, option) => (
          <li {...props} key={option.place_id}>
            <div>
              <div style={{ fontWeight: 'bold' }}>{option.structured_formatting?.main_text}</div>
              <div style={{ fontSize: '0.9em', color: '#666' }}>
                {option.structured_formatting?.secondary_text}
              </div>
            </div>
          </li>
        )}
        loading={!isLoaded}
        loadingText="Loading Google Places..."
        noOptionsText={!isLoaded ? "Loading Google Places..." : "Start typing to search for addresses..."}
        disabled={!isLoaded}
        open={isLoaded && suggestions.length > 0}
        />
      )}
    </FormControl>
  );
};

export default GooglePlacesAutocomplete;
