"use client"

import {
  AdvancedMarker,
  AdvancedMarkerAnchorPoint,
  InfoWindow,
  useAdvancedMarkerRef,
} from "@vis.gl/react-google-maps"
import { useMediaQuery } from "usehooks-ts"

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

import HotelMarkerByType from "@/components/Maps/Markers"
import { trackMapClick } from "@/utils/tracking/destinationPage"

import HotelMapCard from "../../../HotelMapCard"

import type { MarkerProperties } from "@/types/components/maps/destinationMarkers"

interface MarkerProps {
  position: google.maps.LatLngLiteral
  properties: MarkerProperties
}

export default function Marker({ position, properties }: MarkerProps) {
  const [markerRef] = useAdvancedMarkerRef()

  const { setHoveredMarker, setActiveMarker, hoveredMarker, activeMarker } =
    useDestinationPageHotelsMapStore()

  const isDesktop = useMediaQuery("(min-width: 950px)")

  function handleMarkerClick() {
    setActiveMarker(properties.id)
    trackMapClick(properties.name)
  }

  function handleMouseEnter() {
    setHoveredMarker(properties.id)
  }

  function handleMouseLeave() {
    setHoveredMarker(null)
  }

  const isHovered = hoveredMarker === properties.id
  const isActive = activeMarker === properties.id

  return (
    <AdvancedMarker
      ref={markerRef}
      position={position}
      onClick={handleMarkerClick}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      anchorPoint={AdvancedMarkerAnchorPoint.BOTTOM_CENTER}
      zIndex={isActive ? 300 : 0}
    >
      <HotelMarkerByType
        size={isHovered || isActive ? "large" : "small"}
        hotelId={properties.id}
        hotelType={properties.type}
      />

      {isActive && isDesktop && (
        <InfoWindow
          position={position}
          pixelOffset={[0, -24]}
          headerDisabled={true}
          minWidth={450}
        >
          <HotelMapCard
            amenities={properties.amenities.slice(0, 3)}
            tripadvisorRating={properties.tripadvisor}
            hotelName={properties.name}
            image={properties.image}
            url={properties.url}
          />
        </InfoWindow>
      )}
    </AdvancedMarker>
  )
}
