"use client"

import { useSearchParams } from "next/navigation"
import React from "react"

import {
  parseSelectRateSearchParams,
  searchParamsToRecord,
} from "@scandic-hotels/booking-flow/utils/url"
import { SEARCH_TYPE_REDEMPTION } from "@scandic-hotels/trpc/constants/booking"

import TrackingSDK from "@/components/TrackingSDK"
import useLang from "@/hooks/useLang"

import { getValidDates } from "../getValidDates"
import { getTracking } from "./tracking"

import type { ChildrenInRoom } from "@/utils/hotelSearchDetails"

export default function Tracking({
  adultsInRoom,
  childrenInRoom,
  hotelId,
  hotelName,
  noOfRooms,
  country,
  city,
}: {
  adultsInRoom: number[]
  childrenInRoom: ChildrenInRoom
  hotelId: string
  hotelName: string
  noOfRooms: number
  country: string
  city: string
}) {
  const lang = useLang()
  const params = useSearchParams()
  const booking = parseSelectRateSearchParams(searchParamsToRecord(params))

  if (!booking) return null

  const { fromDate, toDate } = getValidDates(booking.fromDate, booking.toDate)

  const { rooms, searchType, bookingCode, city: paramCity } = booking

  const arrivalDate = fromDate.toDate()
  const departureDate = toDate.toDate()

  const { hotelsTrackingData, pageTrackingData } = getTracking(
    lang,
    arrivalDate,
    departureDate,
    adultsInRoom,
    childrenInRoom,
    hotelId,
    hotelName,
    noOfRooms,
    country,
    city,
    paramCity,
    bookingCode,
    searchType === SEARCH_TYPE_REDEMPTION,
    rooms
  )

  return (
    <TrackingSDK pageData={pageTrackingData} hotelInfo={hotelsTrackingData} />
  )
}
