"use client";

import React, { useEffect, useRef } from "react";

interface GoogleMapProps {
  lat?: number;
  lng?: number;
  zoom?: number;
}

export default function GoogleMap({
  lat = 41.263731,
  lng = 69.219434,
  zoom = 17,
}: GoogleMapProps) {
  const mapRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let map: google.maps.Map | null = null;
    let marker: google.maps.Marker | null = null;

    // 🔹 Google script yuklash funksiyasi
    function loadGoogleMapsScript(callback: () => void) {
      if (typeof window.google === "object" && window.google.maps) {
        callback();
        return;
      }

      const existingScript = document.getElementById("googleMaps");
      if (existingScript) {
        existingScript.addEventListener("load", callback);
        return;
      }

      const script = document.createElement("script");
      script.id = "googleMaps";
      script.src = `https://maps.googleapis.com/maps/api/js?key=AIzaSyCiq6iQrcZX6jJMkK_8eT56IeeZDY0LUYo`;
      script.async = true;
      script.defer = true;
      script.onload = callback;
      document.body.appendChild(script);
    }

    // 🔹 Google Mapni ishga tushirish
    function initMap() {
      if (!mapRef.current || !window.google) return;

      map = new window.google.maps.Map(mapRef.current, {
        center: { lat, lng },
        zoom,
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: true,
      });

      // 🔸 Custom marker (svg yoki png)
      marker = new window.google.maps.Marker({
        position: { lat, lng },
        map,
        title: "Bizning joylashuv",
        icon: {
          url: "/custom-marker.svg", // 📍 custom icon
          scaledSize: new window.google.maps.Size(45, 45),
          anchor: new window.google.maps.Point(22, 45),
        },
      });

      // 🔸 Marker click eventi
      marker.addListener("click", () => {
        console.log("Marker clicked!");
        new window.google.maps.InfoWindow({
          content: `
            <div style="font-size:14px; line-height:1.5;">
              <b>Bizning joylashuv:</b><br/>
              Toshkent sh., Mustaqillik maydoni<br/>
              <a href="https://www.google.com/maps?q=${lat},${lng}" target="_blank">Google xaritada ochish</a>
            </div>
          `,
        }).open(map!, marker!);
      });

      // 🔸 Xarita ustida click qilinsa
      map.addListener("click", (event: google.maps.MapMouseEvent) => {
        if (!event.latLng) return;
        const coords = event.latLng.toJSON();
        console.log("Map clicked at:", coords);

        // Markazni o‘zgartirish
        map!.setCenter(coords);

        // Zoomni saqlab qolish (setZoom ishlatish mumkin)
        const currentZoom = map!.getZoom() ?? 17;
        map!.setZoom(currentZoom);

        // Marker joyini o‘zgartirish
        marker!.setPosition(coords);
      });
    }

    // 🔹 Scriptni yuklash
    loadGoogleMapsScript(initMap);

    return () => {
      // tozalash
      if (map) map = null;
      if (marker) marker = null;
    };
  }, [lat, lng, zoom]);

  return (
    <div
      ref={mapRef}
      className="w-full h-[400px] rounded-lg shadow-md overflow-hidden"
    />
  );
}
