import React, { useContext, useEffect, useState } from 'react'
import { Redirect, useLocation } from 'react-router-dom'
import AppContext from '../contexts/AppContext'
import useAuth from 'app/hooks/useAuth'
import { makeStyles, useTheme } from '@material-ui/core/styles'
import KEY from 'app/assets/Key'
import localStorageService from 'app/services/localStorageService'

import { Backdrop, CircularProgress } from '@material-ui/core'
import { connect } from 'react-redux'

const useStyles = makeStyles((theme) => ({
    backdrop: {
        zIndex: theme.zIndex.drawer + 1,
        color: '#fff',
    },
}))

const getUserRoleAuthStatus = (pathname, user) => {
    const token = localStorageService.getItem(KEY.API_TOKEN)
    if (token) {
        //return true
        if (
            pathname === '/dashboard/default' ||
            pathname === '/' ||
            pathname == '/dashboard' ||
            pathname == '/my-profile' ||
            pathname == '/change-password'
        )
            return true

        if (user) {
            if (user.is_sysadmin) {
                return true
            } else {
                let flag = false
                user.listPath.map((e) => {
                    if (e == pathname) flag = true
                })
                return flag
            }
        }
        return false
    } else {
        return false
    }
}

const AuthGuard = ({ children, modalLoading }) => {
    const classes = useStyles()
    const { isAuthenticated, user } = useAuth()

    const [previouseRoute, setPreviousRoute] = useState(null)
    const { pathname } = useLocation()

    const isUserRoleAuthenticated = getUserRoleAuthStatus(pathname, user)
    let authenticated = isAuthenticated && isUserRoleAuthenticated

    // IF YOU NEED ROLE BASED AUTHENTICATION,
    // UNCOMMENT ABOVE TWO LINES, getUserRoleAuthStatus METHOD AND user VARIABLE
    // AND COMMENT OUT BELOW LINE
    // let authenticated = isAuthenticated

    useEffect(() => {
        if (previouseRoute !== null) setPreviousRoute(pathname)
    }, [pathname, previouseRoute])
    if (authenticated)
        return (
            <>
                <Backdrop
                    className={classes.backdrop}
                    open={modalLoading.isVisible}
                >
                    <CircularProgress color="inherit" />
                </Backdrop>
                {children}
            </>
        )
    else {
        return (
            <Redirect
                to={{
                    pathname: '/session/signin',
                    state: { redirectUrl: previouseRoute },
                }}
            />
        )
    }
}

const mapStateToProps = (state) => {
    return {
        modalLoading: state.ModalLoadingReducer,
    }
}
export default connect(mapStateToProps, {})(AuthGuard)
