"use client"

import { useEffect, useState } from "react"

import { useBookingConfirmationStore } from "@/stores/booking-confirmation"

import TrackingSDK from "@/components/TrackingSDK"
import useLang from "@/hooks/useLang"
import { useSearchHistory } from "@/hooks/useSearchHistory"

import { getTracking } from "./tracking"

import type { Room } from "@/types/stores/booking-confirmation"
import type { BookingConfirmation } from "@/types/trpc/routers/booking/confirmation"

export default function Tracking({
  bookingConfirmation,
  refId,
}: {
  bookingConfirmation: BookingConfirmation
  refId: string
}) {
  const lang = useLang()
  const bookingRooms = useBookingConfirmationStore((state) => state.rooms)

  const [loadedBookingConfirmationRefId] = useState(() => {
    if (typeof window !== "undefined") {
      return sessionStorage.getItem("loadedBookingConfirmationRefId")
    }
    return null
  })

  useEffect(() => {
    sessionStorage.setItem("loadedBookingConfirmationRefId", refId)
  }, [refId])

  const searchHistory = useSearchHistory()
  const searchTerm = searchHistory.searchHistory[0]?.name

  if (!bookingRooms.every(Boolean)) {
    return null
  }

  const rooms = bookingRooms.filter((room): room is Room => !!room)

  const { hotelsTrackingData, pageTrackingData, paymentInfo, ancillaries } =
    getTracking(
      lang,
      bookingConfirmation.booking,
      bookingConfirmation.hotel,
      rooms,
      searchTerm
    )

  return (
    <TrackingSDK
      pageData={pageTrackingData}
      hotelInfo={
        loadedBookingConfirmationRefId === refId
          ? undefined
          : hotelsTrackingData
      }
      paymentInfo={
        loadedBookingConfirmationRefId === refId ? undefined : paymentInfo
      }
      ancillaries={
        loadedBookingConfirmationRefId === refId ? undefined : ancillaries
      }
    />
  )
}
