import { PropsWithChildren, createContext, useContext, useEffect, useState } from "react";
import { UserInfoEntity } from "../domain/entities/user_info_entity";
import * as SecureStore from "expo-secure-store";
import axios from "axios";

type AuthContextType = {
    user: UserInfoEntity | null;
    login: (userInfo: UserInfoEntity, token: string) => Promise<void>;
    logout: () => Promise<void>;
    isLoading: boolean;
}

const AuthContext = createContext(
    {
        user: null,
        login: (userInfo: UserInfoEntity, token: string) => {},
        logout: () => {},
        isLoading: true
    } as AuthContextType
);

type AuthContextProviderProps = PropsWithChildren<{}>;

export const AuthContextProvider = ({children}: AuthContextProviderProps) => {
    const [user, setUser] = useState<UserInfoEntity | null>(null);
    const [isLoading, setIsLoading] = useState(true);

    const checkSession = async () => {
        const user = await SecureStore.getItemAsync("user");
        const token = await SecureStore.getItemAsync("token");
        console.log(user);
        console.log(token);
        if (user && token) {
            setUser(JSON.parse(user));
            axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
        }
        setIsLoading(false);
    }

    const login = async (userInfo: UserInfoEntity, token: string) => {
        await SecureStore.setItemAsync("user", JSON.stringify(userInfo));
        await SecureStore.setItemAsync("token", token);
        setUser(userInfo);
        axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
    }

    const logout = async () => {
        await SecureStore.deleteItemAsync("user");
        await SecureStore.deleteItemAsync("token");
        setUser(null);
        axios.defaults.headers.common["Authorization"] = null;
    }

    useEffect(() => {
        checkSession();
    }, []);

    return (
        <AuthContext.Provider value={{user, login, logout, isLoading}}>
            {children}
        </AuthContext.Provider>
    );
}

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (!context) {
        throw new Error("useAuth must be used within an AuthContextProvider");
    }
    return context;
}