"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"
import { CurrencyEnum } from "@/types/enums/currency"

export function LinkedReservation({
  checkInTime,
  checkOutTime,
  refId,
  roomIndex,
}: LinkedReservationProps) {
  const lang = useLang()
  const { data, refetch, isLoading } = trpc.booking.get.useQuery({
    refId,
    lang,
  })
  const {
    setRoom,
    setFormattedTotalCost,
    currencyCode,
    totalBookingPrice,
    totalBookingCheques,
  } = useBookingConfirmationStore((state) => ({
    setRoom: state.actions.setRoom,
    setFormattedTotalCost: state.actions.setFormattedTotalCost,
    currencyCode: state.currencyCode,
    totalBookingPrice: state.totalBookingPrice,
    totalBookingCheques: state.totalBookingCheques,
  }))
  const intl = useIntl()

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

      const formattedTotalCost = totalBookingCheques
        ? formatPrice(
            intl,
            totalBookingCheques,
            CurrencyEnum.CC,
            totalBookingPrice,
            currencyCode
          )
        : formatPrice(intl, totalBookingPrice, currencyCode)

      setFormattedTotalCost(formattedTotalCost)
    }
  }, [
    data,
    roomIndex,
    intl,
    setRoom,
    totalBookingCheques,
    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}
    />
  )
}
