import React from "react";
import Geocode from "react-geocode";
import { GoogleMap, Marker, useLoadScript } from "@react-google-maps/api";
import { GoogleMapsAPI } from "./client-config";

Geocode.setApiKey(GoogleMapsAPI);

interface MapProps {
  lat: number;
  lng: number;
  draggable?: boolean;
  onLocationChange?: (location: string) => void; // Tambahkan onLocationChange
}

function Map({ lat, lng, draggable, onLocationChange }: MapProps) {
  const containerStyle = { width: "100%", height: "400px" };
  const [selected, setSelected] = React.useState<{
    lat: number;
    lng: number;
  } | null>(null);

  const onMarkerDragEnd = async (e: google.maps.MapMouseEvent) => {
    const lat = e.latLng?.lat() ?? 0;
    const lng = e.latLng?.lng() ?? 0;

    try {
      const response = await Geocode.fromLatLng(lat.toString(), lng.toString());
      const address = response.results[0].formatted_address;

      setSelected({ lat, lng });
      if (onLocationChange) {
        onLocationChange(address); // Panggil callback jika tersedia
      }
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <GoogleMap
      zoom={10}
      center={selected || { lat, lng }}
      mapContainerStyle={containerStyle}
    >
      <Marker
        draggable={draggable}
        position={selected || { lat, lng }}
        onDragEnd={onMarkerDragEnd}
      />
    </GoogleMap>
  );
}
