import { useCallback, useEffect } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import { useAccessToken } from '@/store/userStore'
import PageError from '@/pages/sys/error/PageError'
import { useRouter } from '../hooks'

type Props = {
  children: React.ReactNode
}
export default function ProtectedRoute({ children }: Props) {
  const router = useRouter()
  const access_token = useAccessToken()

  const check = useCallback(() => {
    if (!access_token) {
      router.replace('/login')
    }
  }, [router, access_token])

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

  return <ErrorBoundary FallbackComponent={PageError}>{children}</ErrorBoundary>
}
