'use client';
import React, { useState, useRef } from 'react';
import { GoogleMap, LoadScript, Autocomplete } from '@react-google-maps/api';

const libraries: any = ['places']; // Ensure "places" library is loaded

const GoogleMapComponent = ({
  defaultCenter,
  setAddress,
  setPlace
}: {
  defaultCenter: any;
  setAddress: any;
  setPlace: any;
}) => {
  const autocompleteRef = useRef<any>(null);
  const [map, setMap] = useState<any>(null);
  const [center, setCenter] = useState(defaultCenter);
  const [searchValue, setSearchValue] = useState('');

  const handlePlaceSelected = () => {
    if (!autocompleteRef.current) return;
    const place = autocompleteRef.current.getPlace();
    if (place?.geometry) {
      setSearchValue(place?.formatted_address);
      setPlace(place);
      setCenter({
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng()
      });
    }
    setAddress({
      place: searchValue,
      location: {
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng()
      }
    });
  };

  return (
    <LoadScript
      googleMapsApiKey={process.env.NEXT_PUBLIC_GOOGLE_MAP_KEY as string}
      libraries={libraries}
    >
      <div className="flex h-full w-full flex-col gap-2">
        {/* Autocomplete Input */}
        <Autocomplete
          onLoad={(ref) => (autocompleteRef.current = ref)}
          onPlaceChanged={handlePlaceSelected}
        >
          <input
            type="text"
            placeholder="Enter an address"
            className="w-full rounded border p-2"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
          />
        </Autocomplete>

        {/* Google Map */}
        <div className="map-wrapper w-full" style={{ height: '100%' }}>
          <GoogleMap
            center={center}
            zoom={12}
            mapContainerStyle={{ width: '100%', height: '100%' }}
            onLoad={(map) => setMap(map)}
          />
        </div>
      </div>
    </LoadScript>
  );
};

export default GoogleMapComponent;
