"use client"

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

import { REDEMPTION } from "@/constants/booking"

import TrackingSDK from "@/components/TrackingSDK"
import useLang from "@/hooks/useLang"
import { parseSelectRateSearchParams, searchParamsToRecord } from "@/utils/url"

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 === REDEMPTION,
    rooms
  )

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