import { jwtDecode } from "jwt-decode";
import { createContext, ReactNode, useState, useEffect } from "react"
import {
    getAccessToken,
    hydrateTokensFromNativeStorage,
} from "../auth/tokenStorage";

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(() => {
        let cancelled = false;

        const bootstrap = async () => {
            await hydrateTokensFromNativeStorage();
            if (cancelled) {
                return;
            }

            const accessToken = getAccessToken();
            if (accessToken) {
                try {
                    const decodedToken = jwtDecode(accessToken)
                    if (decodedToken.exp && decodedToken.exp * 1000 > Date.now()) {
                        setAuthentication(true);
                    }
                } catch {
                    /* invalid token — stay unauthenticated */
                }
            }
            setLoading(false);
        };

        bootstrap();
        return () => {
            cancelled = true;
        };
    }, [])
    const [ needsNewPassword, setNeedsNewPassword] = useState(initialValues.needsNewPassword)

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

export { AuthContext, AuthProvider }
