import {createContext, FC, ReactNode, useContext, useEffect, useState} from "react";
import * as SplashScreen from "expo-splash-screen";
import auth, {FirebaseAuthTypes} from "@react-native-firebase/auth";
import {useRouter} from "expo-router";
import firestore from "@react-native-firebase/firestore";
import {UserProfile} from "@/hooks/firebase/types/profileTypes";

export enum ProfileType {
    "PARENT" = "parent",
    "CHILD" = "child",
    "CAREGIVER" = "caregiver"
}

interface IAuthContext {
    user: FirebaseAuthTypes.User | null,
    profileType?: ProfileType,
    profileData?: UserProfile
    setProfileData: (profileData: UserProfile) => void
}

const AuthContext = createContext<IAuthContext>(undefined!)

export const AuthContextProvider: FC<{ children: ReactNode }> = ({children}) => {
    const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null)
    const [initializing, setInitializing] = useState(true);
    const [profileType, setProfileType] = useState<ProfileType | undefined>(undefined);
    const [profileData, setProfileData] = useState<UserProfile | undefined>(undefined);

    const {replace} = useRouter()
    const ready = !initializing

    const onAuthStateChanged = async (user: FirebaseAuthTypes.User | null) => {
        setUser(user);

        console.log(user)

        if (user) {
            try {
                const documentSnapshot = await firestore()
                    .collection("Profiles")
                    .doc(user.uid)
                    .get();
                if (documentSnapshot.exists) {
                    setProfileType(documentSnapshot.data()?.userType);
                    setProfileData(documentSnapshot.data() as UserProfile)
                }

            } catch (error) {
                console.error("Error fetching user profile type:", error);
                setProfileType(undefined);
            }
        }

        if (initializing) setInitializing(false);
    }

    useEffect(() => {
        const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
        return subscriber;
    }, []);

    useEffect(() => {
        if (!initializing) {
            SplashScreen.hideAsync();
        }
    }, [initializing]);

    useEffect(() => {
        if (ready && user) {
            replace({pathname: "/(auth)"})
        } else if (ready && !user) {
            replace({pathname: "/(unauth)"})
        }
    }, [user, ready]);

    if (!ready) {
        return null;
    }

    return (
        <AuthContext.Provider value={{user, profileType, profileData, setProfileData}}>
            {children}
        </AuthContext.Provider>
    )
}

export const useAuthContext = () => useContext(AuthContext)!;