"use client"

import { usePathname } from "next/navigation"
import { useEffect, useMemo } from "react"

import { Lang } from "@/constants/languages"
import { useEnterDetailsStore } from "@/stores/enter-details"
import useTrackingStore from "@/stores/tracking"

import { createSDKPageObject } from "@/utils/tracking"

import {
  TrackingChannelEnum,
  TrackingSDKHotelInfo,
  TrackingSDKPageData,
  TrackingSDKUserData,
} from "@/types/components/tracking"

type Props = {
  initialHotelsTrackingData: TrackingSDKHotelInfo
  userTrackingData: TrackingSDKUserData
  lang: Lang
}

export default function EnterDetailsTracking(props: Props) {
  const { initialHotelsTrackingData, userTrackingData, lang } = props
  const currentStep = useEnterDetailsStore((state) => state.currentStep)
  const { getPageLoadTime, hasRun } = useTrackingStore()
  const pathName = usePathname()

  const pageObject = useMemo(() => {
    const pageTrackingData: TrackingSDKPageData = {
      pageId: currentStep,
      domainLanguage: lang,
      channel: TrackingChannelEnum["hotelreservation"],
      pageName: `hotelreservation|${currentStep}`,
      siteSections: `hotelreservation|${currentStep}`,
      pageType: currentStep,
    }

    const trackingData = {
      ...pageTrackingData,
      pathName,
      pageLoadTime: getPageLoadTime(),
    }
    const pageObject = createSDKPageObject(trackingData)
    return pageObject
  }, [currentStep, getPageLoadTime, lang, pathName])

  const hotelDetailsData = useMemo(() => {
    const data: TrackingSDKHotelInfo = { ...initialHotelsTrackingData }
    return data
  }, [initialHotelsTrackingData])

  useEffect(() => {
    if (!hasRun) {
      return
    }
    console.log("TRACKING: Tracking RouterTransition pageViewEnd", pageObject)
    console.log(
      "TRACKING: Tracking RouterTransition userData",
      userTrackingData
    )
    console.log(
      "TRACKING: Tracking RouterTransition hotelInfo",
      hotelDetailsData
    )
    window.adobeDataLayer.push({
      event: "pageViewEnd",
      pageInfo: pageObject,
      userInfo: userTrackingData,
      hotelInfo: hotelDetailsData,
    })
  }, [userTrackingData, hasRun, pageObject, hotelDetailsData])

  return null
}
