import { useRouter } from 'next/router'
import queryString from 'query-string'
import * as React from 'react'
import { useCurrentUser } from '../../../hooks/user/useCurrentUser'

interface IAuthRequiredWrapperProps {
  children: React.ReactNode
}

const AuthRequiredWrapper: React.FunctionComponent<IAuthRequiredWrapperProps> = ({ children }) => {
  const { isLoggedIn } = useCurrentUser()

  const router = useRouter()

  React.useEffect(() => {
    if (!isLoggedIn) {
      router.prefetch('/auth/login')
    }
  }, [router, isLoggedIn])

  const Children = React.Children.map(children, (child: any) => {
    return React.cloneElement(
      child,
      isLoggedIn
        ? {}
        : {
            onClick: () => {
              router.push({
                pathname: '/auth/login',
                query: queryString.stringify({
                  redirectUrl: router.asPath,
                }),
              })
            },
          },
    )
  })

  return <>{Children}</>
}

export default AuthRequiredWrapper
