"use client"

import { useEffect } from "react"

import { trpc } from "@/lib/trpc/client"
import { useBookingConfirmationStore } from "@/stores/booking-confirmation"

import useLang from "@/hooks/useLang"

import { mapRoomState } from "../../utils"
import Room from "../Room"
import { LinkedReservationCardSkeleton } from "./LinkedReservationCardSkeleton"
import Retry from "./Retry"

import type { LinkedReservationProps } from "@/types/components/hotelReservation/bookingConfirmation/rooms/linkedReservation"

export function LinkedReservation({
  confirmationNumber,
  roomIndex,
}: LinkedReservationProps) {
  const lang = useLang()
  const { data, refetch, isLoading } = trpc.booking.confirmation.useQuery({
    confirmationNumber,
    lang,
  })
  const setRoom = useBookingConfirmationStore((state) => state.actions.setRoom)

  useEffect(() => {
    if (data?.room) {
      const roomData = mapRoomState(data.booking, data.room)
      setRoom(roomData, roomIndex)
    }
  }, [data, roomIndex, setRoom])

  if (isLoading) {
    return <LinkedReservationCardSkeleton />
  }

  if (!data?.room) {
    return <Retry handleRefetch={refetch} />
  }

  return (
    <Room
      img={data.room.images[0]}
      booking={data.booking}
      roomName={data.room.name}
    />
  )
}
