"use client";

import {
  GoogleMap as GoolgeMapComponent,
  Marker,
  useJsApiLoader,
  Autocomplete,
} from "@react-google-maps/api";
import React, { useEffect, useRef, useState } from "react";

import { useTranslations } from "next-intl";
import { Input } from "../ui/input";
import { Skeleton } from "../ui/skeleton";
import { useRouter } from "nextjs-toploader/app";
const containerStyle = {
  width: "100%",
  height: "100%",
  minHeight: "250px",
};
interface Position {
  lng: number;
  lat: number;
}

interface GoogleMapProps {
  onMarkerPositionChange: (position: Position) => void;
  defaultMarkerPostion?: Position;
  activeClick?: boolean;
  className?: any;
}

const GoogleMap: React.FC<GoogleMapProps> = ({
  onMarkerPositionChange,
  defaultMarkerPostion = { lat: 30.0444196, lng: 31.2357116 },
  activeClick = false,
  className,
}) => {
  const router = useRouter();
  const t = useTranslations("");
  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: `${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}`,
    libraries: ["places"],
  });

  const [markerPosition, setMarkerPosition] = useState(defaultMarkerPostion);
  const searchInputRef = useRef<HTMLInputElement | null>(null);
  // const autocompleteRef = useRef<google.maps.places.Autocomplete | null>(null);

  useEffect(() => {
    if (defaultMarkerPostion) {
      setMarkerPosition(defaultMarkerPostion);
    }
  }, [defaultMarkerPostion]);
  const getPlaceCoordinates = () => {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode(
      { address: searchInputRef.current?.value },
      function (results, status) {
        if (status === "OK" && results && results.length > 0) {
          const location = results[0].geometry.location;
          const newPosition = {
            lat: location.lat(),
            lng: location.lng(),
          };
          setMarkerPosition(newPosition);
          onMarkerPositionChange(newPosition);
        } else {
          // alert('Geocode was not successful for the following reason: ' + status);
        }
      }
    );
  };
  // 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);
  //     }
  //   }
  // };
  if (!isLoaded) {
    return <Skeleton className="h-full" />;
  }
  const handleMarkerDragEnd = (event: google.maps.MapMouseEvent) => {
    if (event.latLng) {
      const newPosition = {
        lat: event.latLng.lat(),
        lng: event.latLng.lng(),
      };
      setMarkerPosition(newPosition);
      onMarkerPositionChange(newPosition);
    }
  };
  return (
    <div className={`w-full h-full relative z-0  ${className}`}>
      <div className="relative w-full h-full min-h-[250px]">
        <div className="absolute top-12 xs:top-0 right-0 z-[2] rounded-xl m-3 flex gap-4 items-center">
          <Autocomplete onPlaceChanged={getPlaceCoordinates} className="w-full">
            <Input
              placeholder={"search_location"}
              className="border border-secondarytext bg-white md:min-w-[300px]"
              ref={searchInputRef}
            />
          </Autocomplete>
        </div>
        <GoolgeMapComponent
          options={{
            zoomControl: true,
            streetViewControl: false,
            mapTypeControl: true,
            fullscreenControl: false,
          }}
          mapContainerStyle={containerStyle}
          zoom={14}
          center={markerPosition}
          onClick={handleMarkerDragEnd}
        >
          <Marker
            {...(activeClick && {
              onClick: () => {
                router.push(
                  `https://maps.google.com/?q=${markerPosition.lat},${markerPosition.lng}`
                );
              },
            })}
            draggable
            onDragEnd={handleMarkerDragEnd}
            position={markerPosition}
          />
        </GoolgeMapComponent>
      </div>
    </div>
  );
};

export default GoogleMap;
