import { cookies } from "next/headers"

import { TrackingSDK } from "@scandic-hotels/tracking/TrackingSDK"
import {
  TrackingChannelEnum,
  type TrackingSDKPageData,
} from "@scandic-hotels/tracking/types"

import FindMyBooking from "@/components/HotelReservation/FindMyBooking"
import { getIntl } from "@/i18n"

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

import type { AdditionalInfoCookieValue } from "@scandic-hotels/booking-flow/types/components/findMyBooking/additionalInfoCookieValue"
import type { Lang } from "@scandic-hotels/common/constants/language"

import type { FindMyBookingErrorEnum } from "@/components/HotelReservation/FindMyBooking/utils"

export default async function GetBookingPage(
  props: PageProps<"/[lang]/hotelreservation/get-booking">
) {
  const params = await props.params
  const lang = params.lang as Lang

  const pageTrackingData: TrackingSDKPageData = {
    pageId: "get-booking",
    domainLanguage: lang,
    channel: TrackingChannelEnum["hotelreservation"],
    pageName: "get-booking",
    siteSections: "hotelreservation|get-booking",
    pageType: "hotelreservationsget-booking",
    siteVersion: "new-web",
  }

  const searchParams = await props.searchParams
  const error = searchParams.error as FindMyBookingErrorEnum | undefined
  const cookieStore = await cookies()

  const previousValuesCookie = cookieStore.get("bv")?.value

  let defaultValues: AdditionalInfoCookieValue | undefined
  // Only prepopulate previous values if there is an error
  if (previousValuesCookie && error) {
    defaultValues = JSON.parse(previousValuesCookie)
  }

  return (
    <main className={styles.main}>
      <TrackingSDK pageData={pageTrackingData} />
      <div className={styles.form}>
        <FindMyBooking error={error} defaultValues={defaultValues} />
      </div>
    </main>
  )
}

export async function generateMetadata() {
  const intl = await getIntl()

  return {
    title: intl.formatMessage({
      id: "booking.findBooking",
      defaultMessage: "Find booking",
    }),
  }
}
