"use client";

import { FillLocationIcon } from "@/assets/svgs/Icons";
import {
  Autocomplete,
  GoogleMap,
  Marker,
  useJsApiLoader,
} from "@react-google-maps/api";
import React, { useRef, useState, useEffect } from "react";
import { IoSearch } from "react-icons/io5";

interface Position {
  lat: number;
  lng: number;
}

interface GoogleMapProps {
  onLocationChange?: (locationData: {
    address: string;
    lat: number;
    lng: number;
  }) => void;
  defaultMarkerPosition?: any;
  className?: string;
}

const MapInput: React.FC<GoogleMapProps> = ({
  onLocationChange,
  defaultMarkerPosition = { lat: 30.9585477, lng: 31.1613696 },
  className,
}) => {
  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: `${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}`,
    libraries: ["places"],
  });

  const [markerPosition, setMarkerPosition] = useState<Position | null>(defaultMarkerPosition);
  const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [formattedAddress, setFormattedAddress] = useState<string | null>("");

  useEffect(() => {
    setMarkerPosition(defaultMarkerPosition); 
    if (defaultMarkerPosition) fetchAddress(defaultMarkerPosition.lat, defaultMarkerPosition.lng);
  }, []);

  const fetchAddress = (lat: number, lng: number) => {
    const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;;
    fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=false&key=${apiKey}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.results[0]) {
          const address = data.results[0].formatted_address;
          setFormattedAddress(address);
          onLocationChange?.({
            address,
            lat,
            lng,
          });
        }
      });
  };

  const handlePlaceSelect = () => {
    if (autocompleteRef.current) {
      const place = autocompleteRef.current.getPlace();
      if (place.geometry && place.geometry.location) {
        const newPosition = {
          lat: place.geometry.location.lat(),
          lng: place.geometry.location.lng(),
        };
        setMarkerPosition(newPosition);
        setFormattedAddress(place.formatted_address || "");
        onLocationChange?.({
          address: place.formatted_address || "",
          lat: newPosition.lat,
          lng: newPosition.lng,
        });
      }
    }
  };

  const handleMarkerDragEnd = (event: google.maps.MapMouseEvent) => {
    if (event.latLng) {
      const newPosition = {
        lat: event.latLng.lat(),
        lng: event.latLng.lng(),
      };
      setMarkerPosition(newPosition);
      fetchAddress(newPosition.lat, newPosition.lng);
    }
  };

  if (!isLoaded) {
    return <></>;
  }

  return (
    <div className={`w-full ${className}`}>

        <div className="relative w-full h-[450px] overflow-hidden">
          <div className="absolute top-5 left-1/2 -translate-x-1/2 z-10 w-[96%] rounded-xl overflow-hidden bg-white mb-4">
            <Autocomplete
              onLoad={(autocomplete) => (autocompleteRef.current = autocomplete)}
              onPlaceChanged={handlePlaceSelect}
            >
              <div className="relative">
                <IoSearch  className="absolute top-1/2 size-4 -translate-y-1/2 start-4 text-gray-400 z-[1]"  />
                <input
                  ref={inputRef}
                  value={formattedAddress || ""}
                  defaultValue={defaultMarkerPosition?.location_description}
                  onChange={(e) => setFormattedAddress(e.target.value)}
                  type="text"
                  placeholder="Enter location"
                  className="w-full py-3 ps-10 border-none focus:outline-none text-gray-300"
                />
              </div>
            </Autocomplete>
          </div>
          <GoogleMap
            options={{
              zoomControl: true,
              streetViewControl: false,
              mapTypeControl: false,
              fullscreenControl: false,
            }}
            mapContainerStyle={{ width: "100%", height: "100%",borderRadius:"12px" }}
            zoom={14}
            center={markerPosition || { lat: 30.9585477, lng: 31.1613696 }}
            
          >
            {markerPosition && (
              <Marker
                key={markerPosition.lat + markerPosition.lng}
                position={markerPosition}
                draggable={true}
                onDragEnd={handleMarkerDragEnd}
              />
            )}
          </GoogleMap>
        </div>
    </div>
  );
};

export default MapInput;
