"use client"

import { useEffect } from "react"
import { useIntl } from "react-intl"

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

import useLang from "@/hooks/useLang"
import { formatPrice } from "@/utils/numberFormatting"

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({
  checkInTime,
  checkOutTime,
  confirmationNumber,
  roomIndex,
}: LinkedReservationProps) {
  const lang = useLang()
  const { data, refetch, isLoading } = trpc.booking.confirmation.useQuery({
    confirmationNumber,
    lang,
  })
  const { setRoom, setFormattedTotalCost, currencyCode, totalBookingPrice } =
    useBookingConfirmationStore((state) => ({
      setRoom: state.actions.setRoom,
      setFormattedTotalCost: state.actions.setFormattedTotalCost,
      currencyCode: state.currencyCode,
      totalBookingPrice: state.totalBookingPrice,
    }))
  const intl = useIntl()

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

      const formattedTotalCost = formatPrice(
        intl,
        totalBookingPrice,
        currencyCode
      )
      setFormattedTotalCost(formattedTotalCost)
    }
  }, [
    data,
    roomIndex,
    setRoom,
    intl,
    totalBookingPrice,
    currencyCode,
    setFormattedTotalCost,
  ])

  if (isLoading) {
    return <LinkedReservationCardSkeleton />
  }

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

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