/* eslint-disable @next/next/no-img-element */
'use client';

import { useEffect, useMemo, useState } from 'react';

import { useLocale } from 'next-intl';

import { APIProvider, Map as GoogleMap, useMap } from '@vis.gl/react-google-maps';
import { createPortal } from 'react-dom';
import Supercluster from 'supercluster';

import { HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW } from '@/components/home/blocks/homepageMapShowcaseConfig';
import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

export interface ImageMarkerItem {
  key: string;
  lat: number;
  lng: number;
  year: number;
  imageId: number;
}

interface ImageMarkerMapProps {
  items: ImageMarkerItem[];
  selectedKeys: ReadonlySet<string>;
  onSelect: (keys: string[]) => void;
  /** "cooperative" when the map sits inside a scrolling page, so the wheel scrolls the page. */
  gestureHandling?: 'greedy' | 'cooperative';
  /** Which creation a cluster shows: the newest, or the earliest (steadier while the range grows). */
  representative?: 'newest' | 'earliest';
  /** Bounds to fit the map to; null returns to the Carpathian Basin. */
  fitBounds?: google.maps.LatLngBoundsLiteral | null;
}

type PointProps = { index: number; year: number };
type ClusterProps = { newest: number; newestYear: number };

const MIN_ZOOM = 2;
const MAX_ZOOM = 19;
// Clusters that only split up this close in are (nearly) one place: a click lists them instead.
const LIST_CLUSTER_FROM_ZOOM = 17;
const POINT_SIZE = 44;
const CLUSTER_SIZE = 54;
// Wheel travel for one zoom level when the wheel turns over a marker.
const WHEEL_STEP = 100;

// Muted base map, so the images carry the color.
const MAP_STYLES: google.maps.MapTypeStyle[] = [
  { stylers: [{ saturation: -100 }, { lightness: 20 }] },
  { featureType: 'poi', stylers: [{ visibility: 'off' }] },
  { featureType: 'transit', stylers: [{ visibility: 'off' }] },
  { featureType: 'road', elementType: 'labels', stylers: [{ visibility: 'off' }] },
];

const clusterOptions = (
  representative: 'newest' | 'earliest'
): Supercluster.Options<PointProps, ClusterProps> => ({
  radius: 64,
  maxZoom: MAX_ZOOM,
  // Each cluster shows one creation: "newest" holds the shown one, whichever end it is.
  map: (props) => ({ newest: props.index, newestYear: props.year }),
  reduce: (accumulated, props) => {
    const replace =
      representative === 'newest'
        ? props.newestYear > accumulated.newestYear
        : props.newestYear < accumulated.newestYear ||
          (props.newestYear === accumulated.newestYear && props.newest < accumulated.newest);
    if (replace) {
      accumulated.newestYear = props.newestYear;
      accumulated.newest = props.newest;
    }
  },
});

type Feature = Supercluster.ClusterFeature<ClusterProps> | Supercluster.PointFeature<PointProps>;

/** An OverlayView pane to portal HTML markers into, re-rendered whenever the map redraws it. */
function useOverlayPane(map: google.maps.Map | null) {
  const [pane, setPane] = useState<{
    container: HTMLDivElement;
    projection: google.maps.MapCanvasProjection;
    frame: number;
  } | null>(null);

  useEffect(() => {
    if (!map) return;
    const container = document.createElement('div');
    google.maps.OverlayView.preventMapHitsAndGesturesFrom(container);

    class MarkerOverlay extends google.maps.OverlayView {
      onAdd() {
        this.getPanes()?.overlayMouseTarget.appendChild(container);
      }
      draw() {
        const projection = this.getProjection();
        setPane((current) => ({ container, projection, frame: (current?.frame ?? 0) + 1 }));
      }
      onRemove() {
        container.remove();
      }
    }

    const overlay = new MarkerOverlay();
    overlay.setMap(map);
    return () => {
      overlay.setMap(null);
      setPane(null);
    };
  }, [map]);

  return pane;
}

function ImageMarkersLayer({
  items,
  selectedKeys,
  onSelect,
  representative = 'newest',
  fitBounds,
}: ImageMarkerMapProps) {
  const map = useMap();
  const pane = useOverlayPane(map);
  const [viewport, setViewport] = useState<{
    bbox: [number, number, number, number];
    zoom: number;
  } | null>(null);

  const index = useMemo(
    () =>
      new Supercluster<PointProps, ClusterProps>(clusterOptions(representative)).load(
        items.map((item, itemIndex) => ({
          type: 'Feature',
          geometry: { type: 'Point', coordinates: [item.lng, item.lat] },
          properties: { index: itemIndex, year: item.year },
        }))
      ),
    [items, representative]
  );

  // Clusters are recomputed when the map settles after a pan or zoom.
  useEffect(() => {
    if (!map) return;
    const listener = map.addListener('idle', () => {
      const bounds = map.getBounds();
      if (!bounds) return;
      const northEast = bounds.getNorthEast();
      const southWest = bounds.getSouthWest();
      setViewport({
        bbox: [southWest.lng(), southWest.lat(), northEast.lng(), northEast.lat()],
        zoom: Math.floor(map.getZoom() ?? HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.zoom),
      });
    });
    return () => listener.remove();
  }, [map]);

  useEffect(() => {
    if (!map || fitBounds === undefined) return;
    if (fitBounds) {
      map.fitBounds(fitBounds, 48);
    } else {
      map.setCenter(HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.center);
      map.setZoom(HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.zoom);
    }
  }, [map, fitBounds]);

  // The markers keep their events from the map, so a Ctrl+wheel over one would zoom the browser
  // page. Zoom the map instead, around the cursor, as it does everywhere else.
  // The pane object changes on every redraw; its container stays the same.
  const paneContainer = pane?.container;
  useEffect(() => {
    if (!map || !paneContainer) return;
    let travel = 0;
    const onWheel = (event: WheelEvent) => {
      if (!event.ctrlKey && !event.metaKey) return;
      event.preventDefault();
      travel += event.deltaY;
      if (Math.abs(travel) < WHEEL_STEP) return;
      const zoom = map.getZoom();
      const projection = map.getProjection();
      const bounds = map.getBounds();
      if (zoom === undefined || !projection || !bounds) return;
      const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom + (travel < 0 ? 1 : -1)));
      travel = 0;
      if (nextZoom === zoom) return;

      const box = map.getDiv().getBoundingClientRect();
      const x = event.clientX - box.left;
      const y = event.clientY - box.top;
      const northWest = projection.fromLatLngToPoint(
        new google.maps.LatLng(bounds.getNorthEast().lat(), bounds.getSouthWest().lng())
      );
      if (!northWest) return;
      const scale = 2 ** zoom;
      const nextScale = 2 ** nextZoom;
      const cursorX = northWest.x + x / scale;
      const cursorY = northWest.y + y / scale;
      const center = projection.fromPointToLatLng(
        new google.maps.Point(
          cursorX + (box.width / 2 - x) / nextScale,
          cursorY + (box.height / 2 - y) / nextScale
        )
      );
      if (center) map.moveCamera({ center, zoom: nextZoom });
    };
    paneContainer.addEventListener('wheel', onWheel, { passive: false });
    return () => paneContainer.removeEventListener('wheel', onWheel);
  }, [map, paneContainer]);

  const features = useMemo(
    () => (viewport ? (index.getClusters(viewport.bbox, viewport.zoom) as Feature[]) : []),
    [index, viewport]
  );

  if (!pane || !map) return null;

  const handleClick = (feature: Feature) => {
    if (!('cluster' in feature.properties)) {
      onSelect([items[feature.properties.index].key]);
      return;
    }
    const clusterId = (feature.properties as Supercluster.ClusterProperties).cluster_id;
    const expansionZoom = index.getClusterExpansionZoom(clusterId);
    if (expansionZoom >= LIST_CLUSTER_FROM_ZOOM) {
      onSelect(
        index
          .getLeaves(clusterId, Infinity)
          .map((leaf) => items[leaf.properties.index].key)
          .reverse()
      );
      return;
    }
    const [lng, lat] = feature.geometry.coordinates;
    map.panTo({ lat, lng });
    map.setZoom(expansionZoom);
  };

  return createPortal(
    features.map((feature) => {
      const isCluster = 'cluster' in feature.properties;
      const itemIndex = isCluster
        ? (feature.properties as ClusterProps).newest
        : (feature.properties as PointProps).index;
      const item = items[itemIndex];
      if (!item) return null;

      const count = isCluster
        ? (feature.properties as Supercluster.ClusterProperties).point_count
        : 1;
      const [lng, lat] = feature.geometry.coordinates;
      const position = pane.projection.fromLatLngToDivPixel(new google.maps.LatLng(lat, lng));
      if (!position) return null;

      const size = isCluster ? CLUSTER_SIZE : POINT_SIZE;

      return (
        <button
          // Keyed by the shown creation, so a marker only animates in when its image changes.
          key={item.key}
          type="button"
          onClick={() => handleClick(feature)}
          aria-label={isCluster ? `${count} alkotás` : 'Alkotás'}
          className={cn(
            'absolute border-2 bg-white p-0 shadow-md animate-in fade-in zoom-in-50 hover:z-[10000] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mma-blue',
            selectedKeys.has(item.key) ? 'border-[#151720]' : 'border-white'
          )}
          style={{
            left: position.x - size / 2,
            top: position.y - size / 2,
            width: size,
            height: size,
            zIndex: item.year,
          }}
        >
          <img
            src={buildMediaUrl(item.imageId, 'w256')}
            alt=""
            loading="lazy"
            draggable={false}
            className="h-full w-full object-cover"
          />
          {isCluster ? (
            <span className="absolute -right-2 -top-2 min-w-[22px] rounded-full bg-[#151720] px-1.5 py-0.5 text-center text-[11px] font-bold leading-none text-white">
              {count}
            </span>
          ) : null}
        </button>
      );
    }),
    pane.container
  );
}

export default function ImageMarkerMap({
  gestureHandling = 'greedy',
  ...props
}: ImageMarkerMapProps) {
  const locale = useLocale();
  const apiKey = process.env.NEXT_PUBLIC_GMAPS_JAVASCRIPT_API_KEY || '';

  if (!apiKey) {
    return (
      <div className="flex h-full w-full items-center justify-center text-sm text-[#9f1239]">
        A térkép átmenetileg nem elérhető.
      </div>
    );
  }

  return (
    <APIProvider apiKey={apiKey} language={locale} region={locale === 'hu' ? 'HU' : 'EN'}>
      <GoogleMap
        defaultCenter={HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.center}
        defaultZoom={HOMEPAGE_MAP_CARPATHIAN_BASIN_INITIAL_VIEW.zoom}
        minZoom={MIN_ZOOM}
        maxZoom={MAX_ZOOM}
        mapTypeId="roadmap"
        styles={MAP_STYLES}
        gestureHandling={gestureHandling}
        disableDefaultUI
        zoomControl
        clickableIcons={false}
        className="h-full w-full"
      >
        <ImageMarkersLayer {...props} />
      </GoogleMap>
    </APIProvider>
  );
}
