"use client"

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

import useRouterTransitionStore from "@/stores/router-transition"

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

import { TrackingSDKProps } from "@/types/components/tracking"

enum TransitionStatusEnum {
  NotRun = "NotRun",
  Running = "Running",
  Done = "Done",
}

type TransitionStatus = keyof typeof TransitionStatusEnum

export default function RouterTransition({
  pageData,
  userData,
}: TrackingSDKProps) {
  const [loading, setLoading] = useOptimistic(false)
  const [status, setStatus] = useState<TransitionStatus>(
    TransitionStatusEnum.NotRun
  )

  const pathName = usePathname()
  const { isTransitioning, stopRouterTransition } = useRouterTransitionStore()

  useEffect(() => {
    if (isTransitioning && status === TransitionStatusEnum.NotRun) {
      startTransition(() => {
        setStatus(TransitionStatusEnum.Running)
        setLoading(true)
      })
    } else if (
      !loading &&
      isTransitioning &&
      status === TransitionStatusEnum.Running
    ) {
      setStatus(TransitionStatusEnum.Done)
      stopRouterTransition()
    } else if (
      !loading &&
      !isTransitioning &&
      status === TransitionStatusEnum.Done
    ) {
      if (window.adobeDataLayer) {
        const trackingData = { ...pageData, pathName }
        const pageObject = createSDKPageObject(trackingData)

        window.adobeDataLayer.push({
          event: "pageViewEnd",
          pageInfo: pageObject,
          userInfo: userData,
        })
      }
    }
  }, [
    isTransitioning,
    loading,
    status,
    setLoading,
    stopRouterTransition,
    pageData,
    pathName,
    userData,
  ])

  return null
}
