"use client"

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

import { Lang } from "@/constants/languages"
import { useStepsStore } from "@/stores/steps"
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 = useStepsStore((state) => state.currentStep)
  const { getPageLoadTime, hasRun } = useTrackingStore()
  const pathName = usePathname()

  const [hotelsTrackingData, setHotelsTrackingData] = useState(
    initialHotelsTrackingData
  )

  useEffect(() => {
    function trackData() {
      const pageTrackingData: TrackingSDKPageData = {
        pageId: currentStep,
        domainLanguage: lang,
        channel: TrackingChannelEnum["hotelreservation"],
        pageName: `hotelreservation|${currentStep}`,
        siteSections: `hotelreservation|${currentStep}`,
        pageType: currentStep, // TODO: Change to correct
      }

      const trackingData = {
        ...pageTrackingData,
        pathName,
        pageLoadTime: getPageLoadTime(),
      }
      const pageObject = createSDKPageObject(trackingData)
      console.log("TRACKING: Tracking RouterTransition pageViewEnd", pageObject)
      console.log(
        "TRACKING: Tracking RouterTransition userData",
        userTrackingData
      )
      console.log(
        "TRACKING: Tracking RouterTransition hotelInfo",
        hotelsTrackingData
      )
      window.adobeDataLayer.push({
        event: "pageViewEnd",
        pageInfo: pageObject,
        userInfo: userTrackingData,
        hotelInfo: hotelsTrackingData,
      })
    }
    if (hasRun) {
      trackData()
    }
  }, [
    currentStep,
    getPageLoadTime,
    hotelsTrackingData,
    pathName,
    userTrackingData,
    hasRun,
    lang,
  ])

  return null
}
