import { ReactNode, useState, createContext, useEffect, useContext } from "react"
import { AuthContext } from "./AuthContext";
import { AxiosResponse } from "axios";
import { axiosInstance } from "../axiosApi";
import { UserAPI } from "types";

type AccountProviderProps ={
    children? : ReactNode;
}

type IAccountContext = {
    account: UserAPI | undefined;
    setAccount: (account: UserAPI | undefined) => void;
    accountLoading: boolean;
}

const initialValues = {
    account: undefined,
    setAccount: () => {},
    accountLoading: true,
}

const AccountContext = createContext<IAccountContext>(initialValues);

const AccountProvider = ({children}: AccountProviderProps) => {
    const [account, setAccount] = useState<UserAPI | undefined>(initialValues.account);
    const [accountLoading, setAccountLoading] = useState(true); // Add a loading state
    const { authenticated, loading } = useContext(AuthContext);

    async function getAccount (){
        const get_user_response: AxiosResponse<UserAPI> = await axiosInstance.get('/user/')          
            setAccount(get_user_response.data)
    }


    useEffect(() => {
        if(!loading && authenticated){
            getAccount();
            
        }
        setAccountLoading(false);

    }, [authenticated])
    return (
        <AccountContext.Provider value={{account, setAccount, accountLoading}}>
            {children}
        </AccountContext.Provider>
    )
}

export { AccountContext, AccountProvider }