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

import HotelCardDialog from "@/components/HotelReservation/HotelCardDialog"
import Body from "@/components/TempDesignSystem/Text/Body"

import HotelMarker from "../../Markers/HotelMarker"

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

import type { HotelListingMapContentProps } from "@/types/components/hotelReservation/selectHotel/map"

export default function HotelListingMapContent({
  activeHotelPin,
  hotelPins,
  onActiveHotelPinChange,
}: HotelListingMapContentProps) {
  const [hoveredHotelPin, setHoveredHotelPin] = useState<string | null>(null)

  function toggleActiveHotelPin(pinName: string | null) {
    if (onActiveHotelPinChange) {
      onActiveHotelPinChange(activeHotelPin === pinName ? null : pinName)
      setHoveredHotelPin(null)
    }
  }

  function isPinActiveOrHovered(pinName: string) {
    return activeHotelPin === pinName || hoveredHotelPin === pinName
  }

  return (
    <div>
      {hotelPins.map((pin) => {
        const isActiveOrHovered = isPinActiveOrHovered(pin.name)
        return (
          <AdvancedMarker
            key={pin.name}
            className={styles.advancedMarker}
            position={pin.coordinates}
            anchorPoint={AdvancedMarkerAnchorPoint.CENTER}
            zIndex={isActiveOrHovered ? 2 : 0}
            onMouseEnter={() => setHoveredHotelPin(pin.name)}
            onMouseLeave={() => setHoveredHotelPin(null)}
            onClick={() =>
              toggleActiveHotelPin(
                activeHotelPin === pin.name ? null : pin.name
              )
            }
          >
            <div className={styles.dialogContainer}>
              <HotelCardDialog
                isOpen={isActiveOrHovered}
                handleClose={(event: { stopPropagation: () => void }) => {
                  event.stopPropagation()
                  if (activeHotelPin === pin.name) {
                    toggleActiveHotelPin(null)
                  }
                }}
                data={pin}
              />
            </div>
            <span
              className={`${styles.pin} ${isActiveOrHovered ? styles.active : ""}`}
            >
              <span className={styles.pinIcon}>
                <HotelMarker
                  width={16}
                  color={isActiveOrHovered ? "burgundy" : "white"}
                />
              </span>
              <Body
                asChild
                color={isActiveOrHovered ? "white" : "baseTextHighContrast"}
              >
                <span>
                  {pin.memberPrice} {pin.currency}
                </span>
              </Body>
            </span>
          </AdvancedMarker>
        )
      })}
    </div>
  )
}
