import { useAppSelector } from '@/rtk/hooks'
import {
  checkExpToken,
  checkPermissionAdmin,
  removeTokens,
} from '@/rtk/localStorage'
import { selectAuthentication } from '@/rtk/slices/auth'
import type { ReactNode } from 'react'
import { Navigate } from 'react-router-dom'

interface ProtectedRouteProps {
  children: ReactNode
  mode: string
  permission: string
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  mode,
  permission = 'staff',
}) => {
  const auth = useAppSelector(selectAuthentication)
  switch (mode) {
    case 'login':
      return checkExpToken() ? <Navigate to="/" /> : <>{children}</>

    case 'route':
      return !auth.user ? (
        <Navigate to="/login" />
      ) : permission !== 'staff' ? (
        checkPermissionAdmin(permission) ? (
          <>{children}</>
        ) : (
          <Navigate to="/" />
        )
      ) : (
        <>{children}</>
      )

    case 'home':
      if (checkExpToken()) {
        return <>{children}</>
      } else {
        removeTokens()
        return <Navigate to="/login" />
      }

    default:
      break
  }
}

export default ProtectedRoute
