"use client"

import { useEffect, useState } from "react"

import { clearPaymentInfoSessionStorage } from "@scandic-hotels/booking-flow/components/EnterDetails/Payment/helpers"
import { useSearchHistory } from "@scandic-hotels/booking-flow/hooks/useSearchHistory"
import { useBookingConfirmationStore } from "@scandic-hotels/booking-flow/stores/booking-confirmation"
import { TrackingSDK } from "@scandic-hotels/tracking/TrackingSDK"

import useLang from "@/hooks/useLang"

import { getTracking } from "./tracking"

import type { Room } from "@scandic-hotels/booking-flow/types/stores/booking-confirmation"
import type { BookingConfirmation } from "@scandic-hotels/trpc/types/bookingConfirmation"

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

  let trackingData = null

  if (bookingRooms.every(Boolean)) {
    const rooms = bookingRooms.filter((room): room is Room => !!room)
    trackingData = getTracking(
      lang,
      bookingConfirmation.booking,
      bookingConfirmation.hotel,
      rooms,
      searchTerm
    )
  }

  useEffect(() => {
    if (trackingData?.paymentInfo) {
      clearPaymentInfoSessionStorage()
    }
  }, [trackingData])

  if (!trackingData) {
    return null
  }

  const { hotelsTrackingData, pageTrackingData, paymentInfo, ancillaries } =
    trackingData

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