'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from '@/hooks'
import { SplashScreen } from '@/shared/components/loading-screen'
import { getTokenInfo } from '@/utils/token'
import { paths } from '@/routes/paths'
import { useAuthStore } from '@/shared/api/stores/authStore'

type Props = {
  children: React.ReactNode
}

export default function AuthGuard({ children }: Props) {
  const router = useRouter()
  const {logout} = useAuthStore()
  const [checked, setChecked] = useState(false)
  const [loading, setLoading] = useState(true)

  const handleLogout = useCallback(async () => {
    await logout()
    const returnTo = encodeURIComponent(window.location.pathname)
    router.replace(`${paths.auth.jwt.login}?returnTo=${returnTo}`)

    setChecked(false)
    setLoading(false)
  }, [logout, router])

  const checkToken = useCallback(() => {
    const token = localStorage.getItem('token')

    if (token) {
      const tokenInfo = getTokenInfo(token)
      if (!tokenInfo.isValid) {
        handleLogout()
      } else {
        setChecked(true)
        setLoading(false)
      }
    } else {
      handleLogout()
    }
  }, [handleLogout])

  useEffect(() => {
    checkToken()
  }, [checkToken])

  if (loading || !checked) {
    return <SplashScreen />
  }

  return <>{children}</>
}
