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

const libraries: any = ['places'];

const extractAddressPayload = (place: any) => {
  const getComponent = (types: string[]) =>
    place.address_components?.find((comp: any) =>
      types.some((type) => comp.types.includes(type))
    )?.long_name || '';

  return {
    name: place.name || '',
    building_no: getComponent(['street_number']),
    tower: getComponent(['premise', 'subpremise']),
    area: getComponent(['sublocality', 'sublocality_level_1', 'neighborhood']),
    city: getComponent(['locality', 'administrative_area_level_2']),
    nearby_landmark: getComponent(['point_of_interest', 'establishment']),
    lat: place.geometry?.location?.lat().toString() || '',
    long: place.geometry?.location?.lng().toString() || ''
  };
};

const GoogleAutocomplete = ({
  onAddressSelect,
  initialValue = ''
}: {
  onAddressSelect: (address: any) => void;
  initialValue?: string;
}) => {
  const autocompleteRef = useRef<any>(null);
  const [searchValue, setSearchValue] = useState(initialValue);

  const handlePlaceSelected = () => {
    if (!autocompleteRef.current) return;
    const place = autocompleteRef.current.getPlace();

    if (place?.geometry) {
      const addressPayload = extractAddressPayload(place);
      setSearchValue(place.formatted_address || '');
      onAddressSelect(addressPayload);
    }
  };

  useEffect(() => {
    if (initialValue) setSearchValue(initialValue);
  }, [initialValue]);

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

export default GoogleAutocomplete;
