import AsyncStorage from "@react-native-async-storage/async-storage";
import * as React from "react";

interface User {
    email: string;
}

interface AuthContextValue {
    user: User | null;
    isHydrated: boolean;
    login: (email: string, password: string) => Promise<boolean>;
    logout: () => Promise<void>;
}

const authContext = React.createContext<AuthContextValue | undefined>(undefined);
const STORAGE_KEY = "user";

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = React.useState<User | null>(null);
    const [isHydrated, setIsHydrated] = React.useState(false);

    React.useEffect(() => {
        const restoreUser = async () => {
            try {
                const storedUser = await AsyncStorage.getItem(STORAGE_KEY);
                if (storedUser) {
                    setUser(JSON.parse(storedUser) as User);
                }
            } catch (error) {
                console.log("Error restoring user", error);
            } finally {
                setIsHydrated(true);
            }
        };

        restoreUser();
    }, []);
    
    const login = async (email: string, password: string) => {
        const fakeUser = { email };

        await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(fakeUser));
        setUser(fakeUser);
        console.log(fakeUser)
        // await new Promise((resolve) => setTimeout(resolve, 1000));
        return true;
    }

    const logout = async () => {
        await AsyncStorage.removeItem(STORAGE_KEY);
        setUser(null);
    }

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

export function useAuth() {
    const context = React.useContext(authContext);
    if(!context) {
        throw new Error("useAuth must be inside AuthProvider");
    }
    return context;
}


