"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 { getSelectRateTracking } from "./tracking"

export default function Tracking({
  hotelId,
  hotelName,
  country,
  city,
}: {
  hotelId: string
  hotelName: string
  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 } = getSelectRateTracking({
    lang,
    arrivalDate,
    departureDate,
    hotelId,
    hotelName,
    country,
    hotelCity: city,
    paramCity,
    bookingCode,
    isRedemption: searchType === SEARCH_TYPE_REDEMPTION,
    rooms,
  })

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