"use client"

import { useCallback, useEffect, useRef } from "react"

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

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

export default function HotelCardDialogListing({
  hotels,
  activeCard,
  onActiveCardChange,
}: HotelCardDialogListingProps) {
  const hotelsPinData = getHotelPins(hotels)
  const activeCardRef = useRef<HTMLDivElement | null>(null)
  const observerRef = useRef<IntersectionObserver | null>(null)

  const handleIntersection = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const cardName = entry.target.getAttribute("data-name")
          if (cardName) {
            onActiveCardChange(cardName)
          }
        }
      })
    },
    [onActiveCardChange]
  )

  useEffect(() => {
    observerRef.current = new IntersectionObserver(handleIntersection, {
      root: null,
      threshold: 0.5,
    })

    const elements = document.querySelectorAll("[data-name]")
    elements.forEach((el) => observerRef.current?.observe(el))

    return () => {
      elements.forEach((el) => observerRef.current?.unobserve(el))
      observerRef.current?.disconnect()
    }
  }, [handleIntersection])

  useEffect(() => {
    if (activeCardRef.current) {
      // Temporarily disconnect the observer
      observerRef.current?.disconnect()

      activeCardRef.current.scrollIntoView({
        behavior: "smooth",
        block: "nearest",
        inline: "center",
      })

      // Reconnect the observer after scrolling
      const elements = document.querySelectorAll("[data-name]")
      setTimeout(() => {
        elements.forEach((el) => observerRef.current?.observe(el))
      }, 500)
    }
  }, [activeCard])

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