"use client"

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

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

import { HotelData } from "@/types/hotel"

export default function HotelReservationSidePeek({
  hotel,
}: {
  hotel: HotelData | null
}) {
  const activeSidePeek = useSidePeekStore((state) => state.activeSidePeek)
  const hotelId = useSidePeekStore((state) => state.hotelId)
  const roomTypeCode = useSidePeekStore((state) => state.roomTypeCode)
  const close = useSidePeekStore((state) => state.closeSidePeek)
  const lang = useLang()

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

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

  if (activeSidePeek) {
    return (
      <>
        {hotelData && (
          <HotelSidePeek
            hotel={hotelData.data?.attributes}
            activeSidePeek={activeSidePeek}
            close={close}
          />
        )}
        {selectedRoom && (
          <RoomSidePeek
            room={selectedRoom}
            activeSidePeek={activeSidePeek}
            close={close}
          />
        )}
      </>
    )
  }

  return null
}
