/* eslint-disable import/prefer-default-export */
import { useAuth } from 'nlv-auth'
import { Navigate, useLocation } from 'react-router-dom'
import { SplashScreen } from 'ui'

interface AuthRouteProps {
  children: any
  isPublic?: boolean
  isAuth?: boolean
  logo?: string
}

export const AuthRoute = ({ children, isPublic, isAuth, logo }: AuthRouteProps) => {
  const location: any = useLocation()
  const { isAuthenticated, isCheckingAuthentication } = useAuth()

  if (isCheckingAuthentication) {
    return <SplashScreen logo={logo} />
  }

  const privatePathNavigation: string = location.state ? location.state.from : '/'

  const publicPathNavigation: string = location.state ? location.state.from : '/login'

  if (isAuthenticated && isPublic) {
    return <Navigate to={privatePathNavigation} state={{ from: location }} />
  }

  if (!isAuthenticated && isAuth) {
    return <Navigate to={publicPathNavigation} state={{ from: location }} />
  }

  return children
}
