"use client";

import { useEffect, useRef, useState, useCallback, useMemo } from "react";
import L from "leaflet";
import { resolvePropertyCoordinates } from "@/lib/utils/geo";
import { formatNaira, formatCompactNaira } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Compass,
  Bed,
  Bath,
  ArrowUpRight,
  MapPin,
  Maximize2,
  Minimize2,
  X,
  ZoomIn,
  ZoomOut,
} from "lucide-react";
import Link from "next/link";

export interface CatalogMapProps {
  properties: Array<{
    id: string;
    slug: string;
    reference_code?: string;
    title: string;
    listing_type?: string;
    property_type?: string;
    price: number;
    bedrooms?: number;
    bathrooms?: number;
    latitude?: number | null;
    longitude?: number | null;
    state?: { name?: string; slug?: string } | null;
    lga?: { name?: string } | null;
    district?: { name?: string } | null;
    images?: Array<{ url: string; is_primary?: boolean }> | null;
  }>;
  hoveredPropertyId?: string | null;
  onSelectProperty?: (id: string) => void;
  className?: string;
}

export function CatalogMapInner({
  properties,
  hoveredPropertyId,
  onSelectProperty,
  className = "h-full w-full",
}: CatalogMapProps) {
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<L.Map | null>(null);
  const tileLayerRef = useRef<L.TileLayer | null>(null);
  const markersRef = useRef<Map<string, L.Marker>>(new Map());

  const [mapStyle, setMapStyle] = useState<"streets" | "satellite" | "dark">("streets");
  const [selectedProperty, setSelectedProperty] = useState<any | null>(null);
  const [activeRegion, setActiveRegion] = useState<"all" | "lagos" | "abuja">("lagos");
  const [isFullscreen, setIsFullscreen] = useState(false);

  const mapboxToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN || "";

  // Group counts by region
  const regionCounts = useMemo(() => {
    let lagos = 0;
    let abuja = 0;

    properties.forEach((p) => {
      const stateName = (p.state?.name || "").toLowerCase();
      const lgaName = (p.lga?.name || "").toLowerCase();
      const districtName = (p.district?.name || "").toLowerCase();

      if (
        stateName.includes("lagos") ||
        lgaName.includes("eti-osa") ||
        lgaName.includes("ikeja") ||
        districtName.includes("lekki") ||
        districtName.includes("ikoyi") ||
        districtName.includes("victoria")
      ) {
        lagos++;
      } else if (
        stateName.includes("abuja") ||
        stateName.includes("fct") ||
        lgaName.includes("amac") ||
        districtName.includes("maitama") ||
        districtName.includes("asokoro")
      ) {
        abuja++;
      }
    });

    return { total: properties.length, lagos, abuja };
  }, [properties]);

  const getTileConfig = (style: "streets" | "satellite" | "dark") => {
    // High-definition Mapbox Tile API with CartoDB fallback
    if (mapboxToken) {
      switch (style) {
        case "satellite":
          return {
            url: `https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v12/tiles/256/{z}/{x}/{y}@2x?access_token=${mapboxToken}`,
            attribution: '&copy; <a href="https://www.mapbox.com/">Mapbox</a>',
          };
        case "dark":
          return {
            url: `https://api.mapbox.com/styles/v1/mapbox/dark-v11/tiles/256/{z}/{x}/{y}@2x?access_token=${mapboxToken}`,
            attribution: '&copy; <a href="https://www.mapbox.com/">Mapbox</a>',
          };
        default:
          return {
            url: `https://api.mapbox.com/styles/v1/mapbox/streets-v12/tiles/256/{z}/{x}/{y}@2x?access_token=${mapboxToken}`,
            attribution: '&copy; <a href="https://www.mapbox.com/">Mapbox</a>',
          };
      }
    }

    switch (style) {
      case "satellite":
        return {
          url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
          attribution: "&copy; Esri",
        };
      case "dark":
        return {
          url: "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png",
          attribution: '&copy; <a href="https://carto.com/">CARTO</a>',
        };
      default:
        return {
          url: "https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png",
          attribution: '&copy; <a href="https://carto.com/">CARTO</a>',
        };
    }
  };

  // Synchronize Markers
  const syncMarkers = useCallback(() => {
    const map = mapRef.current;
    if (!map) return;

    markersRef.current.forEach((marker) => marker.remove());
    markersRef.current.clear();

    properties.forEach((prop) => {
      const [lng, lat] = resolvePropertyCoordinates(prop);
      if (!isNaN(lng) && !isNaN(lat) && lng !== 0 && lat !== 0) {
        const compactPrice = formatCompactNaira(prop.price);
        const isHovered = hoveredPropertyId === prop.id;

        const customIcon = L.divIcon({
          className: "custom-leaflet-marker-wrapper",
          html: `
            <div id="marker-pill-${prop.id}" class="marker-pill-container group cursor-pointer transition-all duration-200">
              <div class="relative flex flex-col items-center select-none">
                <div class="marker-pill px-3 py-1.5 rounded-full font-bold text-xs shadow-xl border-2 transition-all flex items-center gap-1.5 ${
                  isHovered
                    ? "bg-emerald-600 text-white border-white scale-125 z-40 ring-4 ring-emerald-500/40"
                    : "bg-white dark:bg-[#13151b] text-foreground border-emerald-600 hover:bg-emerald-600 hover:text-white hover:scale-110"
                }">
                  <span class="w-2 h-2 rounded-full ${isHovered ? "bg-white" : "bg-emerald-500"} group-hover:bg-white animate-pulse"></span>
                  <span class="font-extrabold tracking-tight">${compactPrice}</span>
                </div>
                <div class="w-2 h-2 ${
                  isHovered ? "bg-emerald-600 border-white" : "bg-white dark:bg-[#13151b] border-emerald-600"
                } border-r-2 border-b-2 rotate-45 -mt-1 shadow-sm"></div>
              </div>
            </div>
          `,
          iconSize: [80, 36],
          iconAnchor: [40, 36],
        });

        const marker = L.marker([lat, lng], { icon: customIcon }).addTo(map);

        marker.on("click", () => {
          setSelectedProperty(prop);
          onSelectProperty?.(prop.id);
          map.flyTo([lat, lng], 14, { duration: 0.6 });
        });

        markersRef.current.set(prop.id, marker);
      }
    });
  }, [properties, hoveredPropertyId, onSelectProperty]);

  // Initialize Map
  useEffect(() => {
    if (!mapContainerRef.current) return;

    // Clean any prior instance
    if (mapContainerRef.current.children.length > 0) {
      mapContainerRef.current.innerHTML = "";
    }

    const initialCenter: [number, number] = [6.4474, 3.4723]; // Lagos Lekki axis
    const initialZoom = 11.5;

    const map = L.map(mapContainerRef.current, {
      center: initialCenter,
      zoom: initialZoom,
      zoomControl: false,
    });

    const tileConf = getTileConfig(mapStyle);
    const tileLayer = L.tileLayer(tileConf.url, {
      attribution: tileConf.attribution,
      maxZoom: 19,
      tileSize: 256,
      zoomOffset: mapboxToken ? 0 : 0,
    }).addTo(map);

    mapRef.current = map;
    tileLayerRef.current = tileLayer;

    // Delay size calculation to ensure layout is settled
    setTimeout(() => {
      map.invalidateSize();
      syncMarkers();
    }, 100);

    // Debounced Resize Observer
    let lastWidth = 0;
    let lastHeight = 0;
    let resizeTimer: NodeJS.Timeout | null = null;

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        if (Math.abs(width - lastWidth) > 10 || Math.abs(height - lastHeight) > 10) {
          lastWidth = width;
          lastHeight = height;
          if (resizeTimer) clearTimeout(resizeTimer);
          resizeTimer = setTimeout(() => {
            if (mapRef.current) {
              mapRef.current.invalidateSize();
            }
          }, 100);
        }
      }
    });

    if (mapContainerRef.current) {
      resizeObserver.observe(mapContainerRef.current);
    }

    return () => {
      if (resizeTimer) clearTimeout(resizeTimer);
      resizeObserver.disconnect();
      markersRef.current.forEach((m) => m.remove());
      markersRef.current.clear();
      try {
        map.remove();
      } catch {}
      mapRef.current = null;
    };
  }, []);

  // Update Markers on properties change or hover change
  useEffect(() => {
    syncMarkers();
  }, [syncMarkers]);

  // Style change handler
  const handleStyleChange = (style: "streets" | "satellite" | "dark") => {
    setMapStyle(style);
    if (mapRef.current && tileLayerRef.current) {
      const tileConf = getTileConfig(style);
      tileLayerRef.current.setUrl(tileConf.url);
    }
  };

  // Region Focus Controls
  const handleFocusRegion = (region: "all" | "lagos" | "abuja") => {
    setActiveRegion(region);
    const map = mapRef.current;
    if (!map) return;

    if (region === "all") {
      map.flyTo([7.5, 5.5], 5.5, { duration: 0.6 });
    } else if (region === "lagos") {
      map.flyTo([6.4474, 3.4723], 11.5, { duration: 0.6 });
    } else if (region === "abuja") {
      map.flyTo([9.0882, 7.4934], 12.5, { duration: 0.6 });
    }
  };

  // Fit all properties
  const handleFitAll = () => {
    const map = mapRef.current;
    if (!map || properties.length === 0) return;

    const validLatLngs: L.LatLngExpression[] = [];
    properties.forEach((p) => {
      const [lng, lat] = resolvePropertyCoordinates(p);
      if (!isNaN(lng) && !isNaN(lat) && lng !== 0 && lat !== 0) {
        validLatLngs.push([lat, lng]);
      }
    });

    if (validLatLngs.length === 0) {
      map.flyTo([6.4474, 3.4723], 11, { duration: 0.6 });
      return;
    }

    if (validLatLngs.length === 1) {
      map.flyTo(validLatLngs[0], 13, { duration: 0.6 });
      return;
    }

    const bounds = L.latLngBounds(validLatLngs);
    map.fitBounds(bounds, { padding: [50, 50], maxZoom: 13 });
  };

  return (
    <div
      className={`relative rounded-3xl overflow-hidden border border-border bg-card shadow-samara flex flex-col ${
        isFullscreen ? "fixed inset-4 z-50 rounded-2xl shadow-2xl" : className
      }`}
    >
      {/* Map Container */}
      <div ref={mapContainerRef} className="w-full h-full min-h-[400px] flex-1 z-0" />

      {/* Top Floating Control Bar */}
      <div className="absolute top-4 left-4 right-4 flex flex-wrap items-center justify-between gap-2 z-20 pointer-events-none">
        {/* Region Quick-Jump Tabs */}
        <div className="inline-flex rounded-2xl p-1 bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border border-border shadow-lg text-xs pointer-events-auto">
          <button
            onClick={() => handleFocusRegion("all")}
            className={`px-3 py-1.5 rounded-xl font-medium transition-all ${
              activeRegion === "all"
                ? "bg-emerald-600 text-white shadow-sm font-semibold"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            All Nigeria ({regionCounts.total})
          </button>

          {regionCounts.lagos > 0 && (
            <button
              onClick={() => handleFocusRegion("lagos")}
              className={`px-3 py-1.5 rounded-xl font-medium transition-all ${
                activeRegion === "lagos"
                  ? "bg-emerald-600 text-white shadow-sm font-semibold"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Lagos ({regionCounts.lagos})
            </button>
          )}

          {regionCounts.abuja > 0 && (
            <button
              onClick={() => handleFocusRegion("abuja")}
              className={`px-3 py-1.5 rounded-xl font-medium transition-all ${
                activeRegion === "abuja"
                  ? "bg-emerald-600 text-white shadow-sm font-semibold"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Abuja ({regionCounts.abuja})
            </button>
          )}
        </div>

        {/* Style & Zoom Controls */}
        <div className="flex items-center gap-2 pointer-events-auto">
          {/* Map Style Switcher */}
          <div className="inline-flex rounded-2xl p-1 bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border border-border shadow-lg text-xs">
            <button
              onClick={() => handleStyleChange("streets")}
              className={`px-2.5 py-1.5 rounded-xl font-medium transition-all ${
                mapStyle === "streets"
                  ? "bg-emerald-600 text-white shadow-sm font-semibold"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Map
            </button>
            <button
              onClick={() => handleStyleChange("satellite")}
              className={`px-2.5 py-1.5 rounded-xl font-medium transition-all ${
                mapStyle === "satellite"
                  ? "bg-emerald-600 text-white shadow-sm font-semibold"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Satellite
            </button>
            <button
              onClick={() => handleStyleChange("dark")}
              className={`px-2.5 py-1.5 rounded-xl font-medium transition-all ${
                mapStyle === "dark"
                  ? "bg-emerald-600 text-white shadow-sm font-semibold"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              Dark
            </button>
          </div>

          <Button
            variant="outline"
            size="sm"
            onClick={handleFitAll}
            className="h-8 px-3 rounded-2xl bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border-border shadow-lg text-xs gap-1.5 text-foreground hover:bg-muted"
          >
            <Compass className="w-3.5 h-3.5 text-emerald-600" />
            <span>Fit All</span>
          </Button>

          <Button
            variant="outline"
            size="icon"
            onClick={() => setIsFullscreen(!isFullscreen)}
            className="h-8 w-8 rounded-2xl bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border-border shadow-lg text-foreground hover:bg-muted"
            title={isFullscreen ? "Exit Fullscreen" : "Fullscreen"}
          >
            {isFullscreen ? <Minimize2 className="w-3.5 h-3.5" /> : <Maximize2 className="w-3.5 h-3.5" />}
          </Button>
        </div>
      </div>

      {/* Floating Zoom Buttons (Bottom Left) */}
      <div className="absolute bottom-4 left-4 flex flex-col gap-1.5 z-20">
        <Button
          variant="outline"
          size="icon"
          onClick={() => mapRef.current?.zoomIn()}
          className="h-8 w-8 rounded-xl bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border-border shadow-md text-foreground hover:bg-muted"
          title="Zoom In"
        >
          <ZoomIn className="w-4 h-4 text-emerald-600" />
        </Button>
        <Button
          variant="outline"
          size="icon"
          onClick={() => mapRef.current?.zoomOut()}
          className="h-8 w-8 rounded-xl bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border-border shadow-md text-foreground hover:bg-muted"
          title="Zoom Out"
        >
          <ZoomOut className="w-4 h-4 text-emerald-600" />
        </Button>
      </div>

      {/* Selected Property Popup Card */}
      {selectedProperty && (
        <div className="absolute bottom-4 right-4 max-w-sm w-[calc(100%-2rem)] sm:w-88 z-30 animate-in fade-in slide-in-from-bottom-3 duration-200">
          <div className="p-4 rounded-3xl bg-card/95 dark:bg-[#13151b]/95 backdrop-blur-md border border-border shadow-2xl space-y-3">
            {/* Thumbnail Image */}
            <div className="relative aspect-[16/10] rounded-2xl overflow-hidden bg-muted">
              {selectedProperty.images?.[0]?.url ? (
                <img
                  src={selectedProperty.images[0].url}
                  alt={selectedProperty.title}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-xs text-muted-foreground">
                  No preview photo
                </div>
              )}

              <button
                onClick={() => setSelectedProperty(null)}
                className="absolute top-2.5 right-2.5 w-7 h-7 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center transition-colors"
                title="Close"
              >
                <X className="w-3.5 h-3.5" />
              </button>

              {selectedProperty.listing_type && (
                <div className="absolute top-2.5 left-2.5">
                  <Badge className="bg-emerald-600 text-white text-[10px] py-0.5 px-2.5 font-bold uppercase tracking-wider shadow-sm">
                    {selectedProperty.listing_type.replace("_", " ")}
                  </Badge>
                </div>
              )}
            </div>

            {/* Property Details */}
            <div className="space-y-1">
              <p className="text-sm font-bold text-foreground line-clamp-1">
                {selectedProperty.title}
              </p>
              <div className="flex items-baseline justify-between gap-2">
                <span className="text-base font-extrabold text-emerald-600 dark:text-emerald-400">
                  {formatNaira(selectedProperty.price)}
                </span>
                <p className="text-xs text-muted-foreground flex items-center gap-1 truncate">
                  <MapPin className="w-3.5 h-3.5 text-emerald-600 shrink-0" />
                  <span>
                    {selectedProperty.district?.name || selectedProperty.lga?.name || selectedProperty.state?.name || "Nigeria"}
                  </span>
                </p>
              </div>
            </div>

            {/* Stats & Details Action */}
            <div className="flex items-center justify-between pt-2 border-t border-border text-xs text-muted-foreground">
              <div className="flex items-center gap-3">
                {selectedProperty.bedrooms !== undefined && (
                  <span className="flex items-center gap-1 font-medium text-foreground">
                    <Bed className="w-3.5 h-3.5 text-emerald-600" /> {selectedProperty.bedrooms} Beds
                  </span>
                )}
                {selectedProperty.bathrooms !== undefined && (
                  <span className="flex items-center gap-1 font-medium text-foreground">
                    <Bath className="w-3.5 h-3.5 text-emerald-600" /> {selectedProperty.bathrooms} Baths
                  </span>
                )}
              </div>

              <Link
                href={`/properties/${selectedProperty.slug}`}
                className="inline-flex items-center gap-1 font-bold text-xs px-3 py-1.5 rounded-xl bg-emerald-600 text-white hover:bg-emerald-700 transition-colors shadow-sm"
              >
                <span>View Details</span>
                <ArrowUpRight className="w-3.5 h-3.5" />
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
