"use client"

import { useMemo } from "react"

import {
  BOOKING_CONFIRMATION_NUMBER,
  BookingStatusEnum,
} from "@/constants/booking"

import IntroSection from "@/components/HotelReservation/BookingConfirmation/IntroSection"
import StaySection from "@/components/HotelReservation/BookingConfirmation/StaySection"
import SummarySection from "@/components/HotelReservation/BookingConfirmation/SummarySection"
import { tempConfirmationData } from "@/components/HotelReservation/BookingConfirmation/tempConfirmationData"
import LoadingSpinner from "@/components/LoadingSpinner"
import { useHandleBookingStatus } from "@/hooks/booking/useHandleBookingStatus"

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

const maxRetries = 10
const retryInterval = 2000

export default function BookingConfirmationPage() {
  const { email, hotel, stay, summary } = tempConfirmationData

  const confirmationNumber = useMemo(() => {
    if (typeof window === "undefined") return ""

    const storedConfirmationNumber = sessionStorage.getItem(
      BOOKING_CONFIRMATION_NUMBER
    )
    // TODO: cleanup stored values
    // sessionStorage.removeItem(BOOKING_CONFIRMATION_NUMBER)
    return storedConfirmationNumber
  }, [])

  const bookingStatus = useHandleBookingStatus(
    confirmationNumber,
    BookingStatusEnum.BookingCompleted,
    maxRetries,
    retryInterval
  )

  if (
    confirmationNumber === null ||
    bookingStatus.isError ||
    (bookingStatus.isFetched && !bookingStatus.data)
  ) {
    // TODO: handle error
    throw new Error("Error fetching booking status")
  }

  if (
    bookingStatus.data?.reservationStatus === BookingStatusEnum.BookingCompleted
  ) {
    return (
      <main className={styles.main}>
        <section className={styles.section}>
          <IntroSection email={email} />
          <StaySection hotel={hotel} stay={stay} />
          <SummarySection summary={summary} />
        </section>
      </main>
    )
  }

  return <LoadingSpinner />
}
