"use client";

import { useEffect, useRef } from "react";

interface PropertyMapProps {
  latitude: number;
  longitude: number;
}

function loadMapsScript(): Promise<void> {
  return new Promise((resolve, reject) => {
    if (typeof google !== "undefined" && google.maps) {
      resolve();
      return;
    }
    const existing = document.getElementById("google-maps-script");
    if (existing) {
      existing.addEventListener("load", () => resolve());
      existing.addEventListener("error", reject);
      return;
    }
    const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY ?? "";
    const script = document.createElement("script");
    script.id = "google-maps-script";
    script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;
    script.async = true;
    script.onload = () => resolve();
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

export default function PropertyMap({ latitude, longitude }: PropertyMapProps) {
  const mapDivRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    loadMapsScript().then(() => {
      if (!mapDivRef.current) return;
      const position = { lat: latitude, lng: longitude };
      const map = new google.maps.Map(mapDivRef.current, {
        center: position,
        zoom: 18,
        mapTypeId: "hybrid",
        tilt: 0,
        mapTypeControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        zoomControl: true,
        scrollwheel: false,
      });
      new google.maps.Marker({
        position,
        map,
        title: "Property location",
      });
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div
      ref={mapDivRef}
      style={{ height: "100%", width: "100%", minHeight: "320px" }}
    />
  );
}
