"use client"

import { useEffect, useState } from "react"

import { TrackingSDK } from "@scandic-hotels/tracking/TrackingSDK"

import { useBookingFlowConfig } from "../../../bookingFlowConfig/bookingFlowConfigContext"
import { clearPaymentInfoSessionStorage } from "../../../components/EnterDetails/Payment/helpers"
import useLang from "../../../hooks/useLang"
import { useBookingConfirmationStore } from "../../../stores/booking-confirmation"
import { getTracking } from "./tracking"

import type { BookingConfirmation } from "@scandic-hotels/trpc/types/bookingConfirmation"

import type { Room } from "../../../types/stores/booking-confirmation"

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

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

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

  let trackingData = null

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

  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
      }
    />
  )
}
