import { jwtDecode } from "jwt-decode";
import { createContext, ReactNode, useState, useEffect } from "react"


type AuthProviderProps = {
    children?: ReactNode;
}

type IAuthContext = {
    authenticated: boolean;
    setAuthentication: (newState: boolean) => void;
    needsNewPassword: boolean;
    setNeedsNewPassword: (newState: boolean) => void;
    loading: boolean;
}

const initialValues = {
    authenticated: false,
    setAuthentication: () => {},
    needsNewPassword: false,
    setNeedsNewPassword: () => {},
    loading: true,
}

const AuthContext = createContext<IAuthContext>(initialValues);


const AuthProvider = ({children}: AuthProviderProps) => {
    

    const [ authenticated, setAuthentication ] = useState(initialValues.authenticated);
    const [loading, setLoading] = useState(true); // Add a loading state

    useEffect(() => {
        console.log('we are in the auth provider')
        const accessToken = localStorage.getItem('access_token');
        if (accessToken) {
            const decodedToken = jwtDecode(accessToken)
            //console.log(decodedToken)
            if(decodedToken.exp){
                //console.log(decodedToken.exp * 1000)
                //console.log(Date.now())
                if (decodedToken.exp * 1000> Date.now()) {
                    console.log('We are setting that we are authenticated')
                    setAuthentication(true);
                }

            }
            
        }
        setLoading(false);
        

    }, [])
    //console.log(authenticated)
    const [ needsNewPassword, setNeedsNewPassword] = useState(initialValues.needsNewPassword)
    

    return (
        <AuthContext.Provider value={{ authenticated, setAuthentication, needsNewPassword, setNeedsNewPassword, loading}}>
            {children}
        </AuthContext.Provider>
    )
}

export { AuthContext, AuthProvider }