"use client";

import { useEffect, useRef } from "react";
import { setOptions, importLibrary } from "@googlemaps/js-api-loader";

const API_KEY = process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY ?? "";

// Configure once at module level (@googlemaps/js-api-loader v2: `key` + `v`)
setOptions({ key: API_KEY, v: "weekly" });

/* ------------------------------------------------------------------ */
/* Picker – click or drag the marker to set position                   */
/* ------------------------------------------------------------------ */
export function LocationMapPickerClient({
  lat,
  lng,
  onChange,
  className = "",
  height = 240,
}: {
  lat: number;
  lng: number;
  onChange: (next: { lat: number; lng: number }) => void;
  className?: string;
  height?: number;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<google.maps.Map | null>(null);
  const markerRef = useRef<google.maps.Marker | null>(null);
  const clickListenerRef = useRef<google.maps.MapsEventListener | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;
    let isMounted = true;

    (async () => {
      const { Map } = (await importLibrary("maps")) as google.maps.MapsLibrary;

      if (!isMounted || !containerRef.current) return;

      const map = new Map(containerRef.current, {
        center: { lat, lng },
        zoom: 12,
        streetViewControl: false,
        mapTypeControl: false,
        fullscreenControl: true,
      });

      // eslint-disable-next-line @typescript-eslint/no-deprecated
      const marker = new google.maps.Marker({
        map,
        position: { lat, lng },
        draggable: true,
        title: "اسحب أو انقر لتحديد الموقع",
      });

      // Click on map → move pin
      clickListenerRef.current = map.addListener(
        "click",
        (e: google.maps.MapMouseEvent) => {
          if (!e.latLng) return;
          const la = e.latLng.lat();
          const ln = e.latLng.lng();
          marker.setPosition({ lat: la, lng: ln });
          onChange({ lat: la, lng: ln });
        },
      );

      // Drag pin directly
      marker.addListener("dragend", () => {
        const pos = marker.getPosition();
        if (!pos) return;
        onChange({ lat: pos.lat(), lng: pos.lng() });
      });

      mapRef.current = map;
      markerRef.current = marker;
    })();

    return () => {
      isMounted = false;
      if (clickListenerRef.current) {
        google.maps.event.removeListener(clickListenerRef.current);
        clickListenerRef.current = null;
      }
      mapRef.current = null;
      markerRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Sync when parent changes lat/lng (e.g. form reset)
  useEffect(() => {
    if (!mapRef.current || !markerRef.current) return;
    const pos = { lat, lng };
    markerRef.current.setPosition(pos);
    mapRef.current.panTo(pos);
  }, [lat, lng]);

  return (
    <div
      ref={containerRef}
      className={`overflow-hidden rounded-xl border border-slate-200 ${className}`}
      style={{ height }}
    />
  );
}

/* ------------------------------------------------------------------ */
/* View – read-only marker for show pages                               */
/* ------------------------------------------------------------------ */
export function LocationMapViewClient({
  lat,
  lng,
  className = "",
  height = 220,
}: {
  lat: number;
  lng: number;
  className?: string;
  height?: number;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<google.maps.Map | null>(null);
  const markerRef = useRef<google.maps.Marker | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;
    let isMounted = true;

    (async () => {
      const { Map } = (await importLibrary("maps")) as google.maps.MapsLibrary;

      if (!isMounted || !containerRef.current) return;

      const map = new Map(containerRef.current, {
        center: { lat, lng },
        zoom: 13,
        streetViewControl: false,
        mapTypeControl: false,
        gestureHandling: "cooperative",
      });

      // eslint-disable-next-line @typescript-eslint/no-deprecated
      const marker = new google.maps.Marker({
        map,
        position: { lat, lng },
      });

      mapRef.current = map;
      markerRef.current = marker;
    })();

    return () => {
      isMounted = false;
      mapRef.current = null;
      markerRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!mapRef.current || !markerRef.current) return;
    const pos = { lat, lng };
    markerRef.current.setPosition(pos);
    mapRef.current.panTo(pos);
  }, [lat, lng]);

  return (
    <div
      ref={containerRef}
      className={`overflow-hidden rounded-xl border border-slate-200 ${className}`}
      style={{ height }}
    />
  );
}
