"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { AlertCircle, MapPinned } from "lucide-react";
import type { Property } from "@/data/types";

type GoogleMapsApi = {
  maps: {
    LatLngBounds: new () => GoogleLatLngBounds;
    Map: new (element: HTMLElement, options: Record<string, unknown>) => GoogleMapInstance;
    Marker: new (options: Record<string, unknown>) => GoogleMarkerInstance;
    Point: new (x: number, y: number) => unknown;
    Size: new (width: number, height: number) => unknown;
  };
};

type GoogleMapInstance = {
  fitBounds: (bounds: GoogleLatLngBounds, padding?: number) => void;
  getZoom: () => number;
  panTo: (position: GoogleLatLngLiteral) => void;
  setCenter: (position: GoogleLatLngLiteral) => void;
  setZoom: (zoom: number) => void;
};

type GoogleMarkerInstance = {
  addListener: (eventName: string, handler: () => void) => void;
  setIcon: (icon: GoogleMarkerIcon) => void;
  setMap: (map: GoogleMapInstance | null) => void;
  setZIndex: (zIndex?: number) => void;
};

type GoogleLatLngBounds = {
  extend: (position: GoogleLatLngLiteral) => void;
};

type GoogleLatLngLiteral = {
  lat: number;
  lng: number;
};

type GoogleMarkerIcon = {
  anchor: unknown;
  scaledSize: unknown;
  url: string;
};

declare global {
  interface Window {
    __elladaGoogleMapsPromise?: Promise<GoogleMapsApi>;
    __ELLADA_ENV?: {
      googleMapsApiKey?: string;
    };
    google?: GoogleMapsApi;
  }
}

interface PropertyPriceMapProps {
  activePropertyId?: string | null;
  className?: string;
  emptyLabel?: string;
  properties: Property[];
  onSelectProperty?: (propertyId: string) => void;
}

function hasValidCoordinates(property: Property) {
  return (
    Number.isFinite(property.location.lat) &&
    Number.isFinite(property.location.lng) &&
    Math.abs(property.location.lat) > 0.001 &&
    Math.abs(property.location.lng) > 0.001
  );
}

function formatMarkerPrice(price: number, dealType: Property["dealType"]) {
  if (dealType === "rent") {
    if (price >= 1000) {
      return `€${(price / 1000).toFixed(price >= 10000 ? 0 : 1)}k`;
    }

    return `€${price}`;
  }

  if (price >= 1000000) {
    return `€${(price / 1000000).toFixed(price >= 10000000 ? 0 : 1)}M`;
  }

  if (price >= 1000) {
    return `€${Math.round(price / 1000)}k`;
  }

  return `€${price}`;
}

function buildMarkerIcon(
  googleMaps: GoogleMapsApi,
  property: Property,
  active: boolean,
): GoogleMarkerIcon {
  const label = formatMarkerPrice(property.price, property.dealType);
  const markerWidth = Math.max(76, label.length * 10 + 30);
  const bubbleHeight = 40;
  const pointerHeight = 10;
  const totalHeight = bubbleHeight + pointerHeight;
  const fill = active
    ? "#d8a03f"
    : property.dealType === "rent"
      ? "#0f9fb6"
      : "#173b63";
  const stroke = active ? "#fef3c7" : "#ffffff";
  const shadowFill = "rgba(15, 23, 42, 0.18)";
  const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" width="${markerWidth}" height="${totalHeight}" viewBox="0 0 ${markerWidth} ${totalHeight}">
      <g>
        <rect x="4" y="5" width="${markerWidth - 8}" height="${bubbleHeight - 6}" rx="18" fill="${shadowFill}" />
        <path d="M${markerWidth / 2 - 7} ${bubbleHeight - 2} L${markerWidth / 2} ${totalHeight - 2} L${markerWidth / 2 + 7} ${bubbleHeight - 2} Z" fill="${shadowFill}" />
        <rect x="2" y="2" width="${markerWidth - 4}" height="${bubbleHeight - 4}" rx="18" fill="${fill}" stroke="${stroke}" stroke-width="2" />
        <path d="M${markerWidth / 2 - 9} ${bubbleHeight - 4} L${markerWidth / 2} ${totalHeight - 4} L${markerWidth / 2 + 9} ${bubbleHeight - 4} Z" fill="${fill}" stroke="${stroke}" stroke-width="2" stroke-linejoin="round" />
        <text x="50%" y="23" text-anchor="middle" font-family="Arial, sans-serif" font-size="14" font-weight="700" fill="#ffffff">${label}</text>
      </g>
    </svg>
  `;

  return {
    anchor: new googleMaps.maps.Point(markerWidth / 2, totalHeight - 2),
    scaledSize: new googleMaps.maps.Size(markerWidth, totalHeight),
    url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svg)}`,
  };
}

function loadGoogleMapsApi(apiKey: string) {
  if (typeof window === "undefined") {
    return Promise.reject(new Error("Google Maps can be loaded only in the browser."));
  }

  if (window.google?.maps) {
    return Promise.resolve(window.google);
  }

  if (!window.__elladaGoogleMapsPromise) {
    window.__elladaGoogleMapsPromise = new Promise<GoogleMapsApi>((resolve, reject) => {
      const existingScript = document.querySelector<HTMLScriptElement>(
        'script[data-google-maps="elladahomes"]',
      );

      const handleLoad = () => {
        if (window.google?.maps) {
          resolve(window.google);
          return;
        }

        reject(new Error("Google Maps script loaded without the maps namespace."));
      };

      const handleError = () => reject(new Error("Google Maps failed to load."));

      if (existingScript) {
        existingScript.addEventListener("load", handleLoad, { once: true });
        existingScript.addEventListener("error", handleError, { once: true });
        return;
      }

      const script = document.createElement("script");
      script.async = true;
      script.dataset.googleMaps = "elladahomes";
      script.defer = true;
      script.src = `https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(apiKey)}&language=bg&region=BG&v=weekly`;
      script.addEventListener("load", handleLoad, { once: true });
      script.addEventListener("error", handleError, { once: true });
      document.head.appendChild(script);
    }).catch((error) => {
      window.__elladaGoogleMapsPromise = undefined;
      throw error;
    });
  }

  return window.__elladaGoogleMapsPromise;
}

export default function PropertyPriceMap({
  activePropertyId = null,
  className,
  emptyLabel = "Няма налични координати за показване на картата.",
  properties,
  onSelectProperty,
}: PropertyPriceMapProps) {
  const apiKey =
    (typeof window !== "undefined"
      ? (window.__ELLADA_ENV?.googleMapsApiKey || "")
      : "") || process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || "";
  const mapRef = useRef<GoogleMapInstance | null>(null);
  const mapElementRef = useRef<HTMLDivElement | null>(null);
  const markersRef = useRef<Map<string, { marker: GoogleMarkerInstance; property: Property }>>(new Map());
  const [mapState, setMapState] = useState<"idle" | "loading" | "ready" | "missing-key" | "error">(
    apiKey ? "idle" : "missing-key",
  );

  const mappableProperties = useMemo(
    () => properties.filter(hasValidCoordinates),
    [properties],
  );

  useEffect(() => {
    if (!apiKey) {
      setMapState("missing-key");
      return;
    }

    let cancelled = false;
    setMapState("loading");

    loadGoogleMapsApi(apiKey)
      .then((googleMaps) => {
        if (cancelled || !mapElementRef.current) {
          return;
        }

        if (!mapRef.current) {
          const firstProperty = mappableProperties[0];
          const center = firstProperty
            ? { lat: firstProperty.location.lat, lng: firstProperty.location.lng }
            : { lat: 37.9838, lng: 23.7275 };

          mapRef.current = new googleMaps.maps.Map(mapElementRef.current, {
            center,
            clickableIcons: false,
            fullscreenControl: true,
            mapTypeControl: false,
            streetViewControl: false,
            zoom: firstProperty ? 11 : 7,
          });
        }

        setMapState("ready");
      })
      .catch(() => {
        if (!cancelled) {
          setMapState("error");
        }
      });

    return () => {
      cancelled = true;
    };
  }, [apiKey, mappableProperties]);

  useEffect(() => {
    const googleMaps = window.google;
    const map = mapRef.current;

    if (mapState !== "ready" || !googleMaps?.maps || !map) {
      return;
    }

    for (const { marker } of markersRef.current.values()) {
      marker.setMap(null);
    }
    markersRef.current.clear();

    if (!mappableProperties.length) {
      return;
    }

    const bounds = new googleMaps.maps.LatLngBounds();

    for (const property of mappableProperties) {
      const marker = new googleMaps.maps.Marker({
        icon: buildMarkerIcon(googleMaps, property, property.id === activePropertyId),
        map,
        position: {
          lat: property.location.lat,
          lng: property.location.lng,
        },
        title: property.title,
        zIndex: property.id === activePropertyId ? 1000 : undefined,
      });

      marker.addListener("mouseover", () => {
        onSelectProperty?.(property.id);
      });

      marker.addListener("click", () => {
        onSelectProperty?.(property.id);

        if (typeof window !== "undefined") {
          window.location.assign(`/properties/${property.id}`);
        }
      });

      markersRef.current.set(property.id, { marker, property });
      bounds.extend({
        lat: property.location.lat,
        lng: property.location.lng,
      });
    }

    if (mappableProperties.length === 1) {
      map.setCenter({
        lat: mappableProperties[0].location.lat,
        lng: mappableProperties[0].location.lng,
      });
      map.setZoom(13);
      return;
    }

    map.fitBounds(bounds, 56);
  }, [activePropertyId, mapState, mappableProperties, onSelectProperty]);

  useEffect(() => {
    const googleMaps = window.google;

    if (mapState !== "ready" || !googleMaps?.maps) {
      return;
    }

    for (const [propertyId, item] of markersRef.current.entries()) {
      item.marker.setIcon(
        buildMarkerIcon(googleMaps, item.property, propertyId === activePropertyId),
      );
      item.marker.setZIndex(propertyId === activePropertyId ? 1000 : undefined);
    }
  }, [activePropertyId, mapState]);

  if (!mappableProperties.length) {
    return (
      <div className={`rounded-2xl border border-border/60 bg-card p-6 ${className || ""}`}>
        <div className="flex h-full min-h-[280px] flex-col items-center justify-center text-center">
          <MapPinned className="mb-4 h-10 w-10 text-muted-foreground" />
          <h3 className="mb-2 text-lg font-semibold text-foreground">Картата не е налична</h3>
          <p className="max-w-sm text-sm leading-relaxed text-muted-foreground">{emptyLabel}</p>
        </div>
      </div>
    );
  }

  if (mapState === "missing-key") {
    return (
      <div className={`rounded-2xl border border-amber-200 bg-amber-50 p-6 ${className || ""}`}>
        <div className="flex h-full min-h-[280px] flex-col items-center justify-center text-center">
          <AlertCircle className="mb-4 h-10 w-10 text-amber-500" />
          <h3 className="mb-2 text-lg font-semibold text-amber-950">Липсва Google Maps API ключ</h3>
          <p className="max-w-sm text-sm leading-relaxed text-amber-900/80">
            Добави <code>NEXT_PUBLIC_GOOGLE_MAPS_API_KEY</code> в <code>.env.local</code>, за
            да се визуализира интерактивната карта с ценови маркери.
          </p>
        </div>
      </div>
    );
  }

  if (mapState === "error") {
    return (
      <div className={`rounded-2xl border border-destructive/20 bg-destructive/5 p-6 ${className || ""}`}>
        <div className="flex h-full min-h-[280px] flex-col items-center justify-center text-center">
          <AlertCircle className="mb-4 h-10 w-10 text-destructive" />
          <h3 className="mb-2 text-lg font-semibold text-foreground">Картата не успя да се зареди</h3>
          <p className="max-w-sm text-sm leading-relaxed text-muted-foreground">
            Провери дали Google Maps ключът е валиден и дали Maps JavaScript API е активирано.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={`rounded-2xl border border-border/60 bg-card p-3 shadow-card ${className || ""}`}>
      <div className="mb-3 flex items-center justify-between gap-3 px-2">
        <div>
          <h3 className="text-sm font-semibold text-foreground">Карта на офертите</h3>
          <p className="text-xs text-muted-foreground">
            {mappableProperties.length} имота с координати и цени по райони
          </p>
        </div>
      </div>

      <div
        ref={mapElementRef}
        className="h-[420px] overflow-hidden rounded-2xl bg-secondary lg:h-[calc(100vh-10rem)]"
      />
    </div>
  );
}
