"use client"
import { use, useEffect } from "react"
import { useIntl } from "react-intl"

import { dt } from "@/lib/dt"

import Caption from "@/components/TempDesignSystem/Text/Caption"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useLang from "@/hooks/useLang"

import { useMyStayRoomDetailsStore } from "../stores/myStayRoomDetailsStore"
import { useMyStayTotalPriceStore } from "../stores/myStayTotalPrice"
import { formatChildBedPreferences } from "../utils"

import styles from "./linkedReservation.module.css"

import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"

interface LinkedReservationProps {
  bookingPromise: Promise<BookingConfirmation | null>
  index: number
}

export default function LinkedReservation({
  bookingPromise,
  index,
}: LinkedReservationProps) {
  const intl = useIntl()
  const lang = useLang()

  const {
    actions: { setRoomPrice },
  } = useMyStayTotalPriceStore()
  const {
    actions: { setRoomDetails },
  } = useMyStayRoomDetailsStore()

  const bookingConfirmation = use(bookingPromise)
  const { booking, room } = bookingConfirmation ?? {}

  useEffect(() => {
    if (booking) {
      const childrenAsString = formatChildBedPreferences({
        childrenAges: booking.childrenAges ?? [],
        childBedPreferences: booking.childBedPreferences ?? [],
      })

      setRoomPrice({
        id: booking.confirmationNumber,
        totalPrice: booking.totalPrice,
        currencyCode: booking.currencyCode,
        isMainBooking: false,
      })

      // Add room details for linked reservation to the store
      setRoomDetails({
        id: booking.confirmationNumber,
        hotelId: booking.hotelId,
        checkInDate: booking.checkInDate,
        checkOutDate: booking.checkOutDate,
        adults: booking.adults,
        children: childrenAsString,
        roomName: room?.name ?? booking.roomTypeCode ?? "",
        roomTypeCode: booking.roomTypeCode ?? "",
        rateCode: booking.rateDefinition.rateCode ?? "",
        bookingCode: booking.bookingCode ?? "",
        isCancelable: booking.isCancelable,
        mainRoom: booking.mainRoom,
      })
    }
  }, [booking, room, setRoomPrice, setRoomDetails])

  if (!booking) return null

  const fromDate = dt(booking.checkInDate).locale(lang)
  const toDate = dt(booking.checkOutDate).locale(lang)

  const adultsMsg = intl.formatMessage(
    { id: "{adults, plural, one {# adult} other {# adults}}" },
    {
      adults: booking.adults,
    }
  )

  const childrenMsg = intl.formatMessage(
    {
      id: "{children, plural, one {# child} other {# children}}",
    },
    {
      children: booking.childrenAges.length,
    }
  )

  const adultsOnlyMsg = adultsMsg
  const adultsAndChildrenMsg = [adultsMsg, childrenMsg].join(", ")

  return (
    <article className={styles.linkedReservation}>
      <div className={styles.title}>
        <Subtitle color="burgundy">
          {intl.formatMessage(
            { id: "Room {roomIndex}" },
            {
              roomIndex: index + 2,
            }
          )}
        </Subtitle>
      </div>
      <div className={styles.details}>
        <Caption textTransform="uppercase" type="bold">
          {intl.formatMessage({ id: "Reference" })} {booking.confirmationNumber}
        </Caption>
        <div>
          <Caption color="uiTextHighContrast">
            {booking.childrenAges.length > 0
              ? adultsAndChildrenMsg
              : adultsOnlyMsg}
          </Caption>
        </div>
      </div>
      <div className={styles.dates}>
        <div className={styles.date}>
          <Caption
            type="bold"
            textTransform="uppercase"
            color="uiTextHighContrast"
          >
            {intl.formatMessage({ id: "Check-in" })}
          </Caption>
          <Caption color="uiTextHighContrast">
            {`${fromDate.format("dddd, D MMMM")} `}
          </Caption>
        </div>
        <div className={styles.date}>
          <Caption
            type="bold"
            textTransform="uppercase"
            color="uiTextHighContrast"
          >
            {intl.formatMessage({ id: "Check-out" })}
          </Caption>
          <Caption color="uiTextHighContrast">
            {`${toDate.format("dddd, D MMMM")} `}
          </Caption>
        </div>
      </div>
    </article>
  )
}
