"use client"

import { useEffect } from "react"

import { trpc } from "@/lib/trpc/client"
import useSidePeekStore from "@/stores/sidepeek"

import AmenitiesSidePeek from "@/components/SidePeeks/AmenitiesSidePeek"
import HotelSidePeek from "@/components/SidePeeks/HotelSidePeek"
import RoomSidePeek from "@/components/SidePeeks/RoomSidePeek"
import useLang from "@/hooks/useLang"

export default function HotelReservationSidePeek() {
  const { activeSidePeek, hotelId, roomTypeCode, showCTA } = useSidePeekStore(
    (state) => ({
      activeSidePeek: state.activeSidePeek,
      hotelId: state.hotelId,
      roomTypeCode: state.roomTypeCode,
      showCTA: state.showCTA,
    })
  )
  const closeFn = useSidePeekStore((state) => state.closeSidePeek)
  const lang = useLang()

  const { data: hotelData } = trpc.hotel.get.useQuery(
    {
      hotelId: hotelId ?? "",
      language: lang,
      isCardOnlyPayment: false,
    },
    {
      enabled: !!hotelId,
    }
  )

  const selectedRoom = hotelData?.roomCategories.find((room) =>
    room.roomTypes.some((type) => type.code === roomTypeCode)
  )

  useEffect(() => {
    if (activeSidePeek) {
      window.history.pushState(null, "", window.location.href)
    }
  }, [activeSidePeek])

  useEffect(() => {
    function handlePopState() {
      if (activeSidePeek) {
        closeFn()
      }
    }

    window.addEventListener("popstate", handlePopState)

    return () => {
      window.removeEventListener("popstate", handlePopState)
    }
  }, [activeSidePeek, closeFn])

  if (activeSidePeek) {
    return (
      <>
        {hotelData && (
          <>
            <HotelSidePeek
              additionalHotelData={hotelData.additionalData}
              hotel={{ ...hotelData.hotel, url: hotelData.url }}
              restaurants={hotelData.restaurants}
              activeSidePeek={activeSidePeek}
              close={closeFn}
              showCTA={showCTA}
            />
            <AmenitiesSidePeek
              hotel={{ ...hotelData.hotel, url: hotelData.url }}
              restaurants={hotelData.restaurants}
              additionalHotelData={hotelData.additionalData}
              activeSidePeek={activeSidePeek}
              close={closeFn}
            />
          </>
        )}
        {selectedRoom && (
          <RoomSidePeek
            room={selectedRoom}
            activeSidePeek={activeSidePeek}
            close={closeFn}
          />
        )}
      </>
    )
  }

  return null
}
