"use client"

import {
  AdvancedMarker,
  AdvancedMarkerAnchorPoint,
} from "@vis.gl/react-google-maps"
import { useCallback } from "react"

import { useDestinationPageHotelsMapStore } from "@/stores/destination-page-hotels-map"

import { trackMapClick } from "@/utils/tracking/destinationPage"

import styles from "./clusterMarker.module.css"

interface ClusterMarkerProps {
  position: google.maps.LatLngLiteral
  size: number
  sizeAsText: string
  onMarkerClick?: (position: google.maps.LatLngLiteral) => void
  hotelIds: number[]
}

export default function ClusterMarker({
  position,
  size,
  sizeAsText,
  onMarkerClick,
  hotelIds,
}: ClusterMarkerProps) {
  const { hoveredMarker, activeMarker } = useDestinationPageHotelsMapStore()
  const isActive =
    hotelIds.includes(Number(hoveredMarker)) ||
    hotelIds.includes(Number(activeMarker))

  const handleClick = useCallback(() => {
    if (onMarkerClick) {
      onMarkerClick(position)
    }
    trackMapClick(`cluster with hotelIds: ${hotelIds.join(",")}`)
  }, [onMarkerClick, position, hotelIds])

  return (
    <AdvancedMarker
      position={position}
      zIndex={size}
      onClick={handleClick}
      className={`${styles.clusterMarker} ${isActive ? styles.hoveredChild : ""}`}
      anchorPoint={AdvancedMarkerAnchorPoint.CENTER}
    >
      <span className={styles.count}>{sizeAsText}</span>
    </AdvancedMarker>
  )
}
