"use client"

import { useEffect, useRef } from "react"

import HotelCardDialog from "../HotelCardDialog"
import { getHotelPins } from "./utils"

import type { HotelData } from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"

export default function HotelCardDialogListing({
  hotels,
  activeCard,
}: {
  hotels: HotelData[]
  activeCard: string | null | undefined
}) {
  const hotelsPinData = getHotelPins(hotels)
  const activeCardRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (activeCardRef.current) {
      activeCardRef.current.scrollIntoView({
        behavior: "smooth",
        block: "nearest",
        inline: "center",
      })
    }
  }, [activeCard])

  return (
    <>
      {hotelsPinData?.length &&
        hotelsPinData.map((data) => {
          const isActive = data.name === activeCard
          return (
            <div key={data.name} ref={isActive ? activeCardRef : null}>
              <HotelCardDialog
                data={data}
                isOpen={!!activeCard}
                handleClose={() => {}}
              />
            </div>
          )
        })}
    </>
  )
}
