import { Suspense } from "react"

import { BookingFlowConfig } from "../../bookingFlowConfig/bookingFlowConfig"
import {
  getPageSettingsBookingCode,
  isBookingWidgetHidden,
} from "../../trpc/memoizedRequests"
import BookingWidgetClient from "./Client"
import { BookingWidgetSkeleton } from "./Skeleton"

import type { Lang } from "@scandic-hotels/common/constants/language"
import type { Child } from "@scandic-hotels/trpc/types/child"
import type { VariantProps } from "class-variance-authority"

import type { BookingSearchType } from "../../misc/searchType"
import type { bookingWidgetVariants } from "./BookingWidgetForm/variants"

export { BookingWidgetSkeleton } from "./Skeleton"

export type GuestsRoom = {
  adults: number
  childrenInRoom: Child[]
}

export type BookingWidgetSearchData = {
  city?: string
  hotelId?: string
  fromDate?: string
  toDate?: string
  rooms?: GuestsRoom[]
  bookingCode?: string
  searchType?: BookingSearchType
}

export type BookingWidgetType = VariantProps<
  typeof bookingWidgetVariants
>["type"]

export type BookingWidgetProps = {
  type?: BookingWidgetType
  booking: BookingWidgetSearchData
  lang: Lang
  config: BookingFlowConfig
}

export async function BookingWidget({ config, ...props }: BookingWidgetProps) {
  return (
    <BookingFlowConfig config={config}>
      <Suspense fallback={<BookingWidgetSkeleton config={config} />}>
        <InternalBookingWidget {...props} />
      </Suspense>
    </BookingFlowConfig>
  )
}

async function InternalBookingWidget({
  lang,
  type,
  booking,
}: Omit<BookingWidgetProps, "config">) {
  const isHidden = await isBookingWidgetHidden(lang)

  if (isHidden) {
    return null
  }

  let pageSettingsBookingCodePromise: Promise<string> | null = null
  if (!booking.bookingCode) {
    pageSettingsBookingCodePromise = getPageSettingsBookingCode(lang)
  }

  return (
    <BookingWidgetClient
      type={type}
      data={booking}
      pageSettingsBookingCodePromise={pageSettingsBookingCodePromise}
    />
  )
}
