import { DEV_USER_ID } from "@env";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";
import React, { createContext, useContext, useEffect, useState } from "react";
import { handleSignOut, onAuthStateChanged } from "../auth/firebase-auth";
import { useAuthHeader } from "../graphql/client";

interface AuthContextType {
	isLoggedIn: boolean;
	isLoading: boolean;
	user: FirebaseAuthTypes.User | null;
	logOut: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
	children,
}) => {
	const { setAuthHeader } = useAuthHeader();

	const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
	const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
	const [isLoading, setIsLoading] = useState<boolean>(true); // this is for a LoadingContext (auth, app reloads, foreground etc)
 
	const authStateChangeCallback =  async (user) => {
		console.log("user:", user);
		if (user) {
			const token = await user.getIdToken();
			if (token) {
				await AsyncStorage.setItem("token", token);
				setAuthHeader({ key: "Authorization", value: token });
				setUser(user);
				setIsLoggedIn(true);
				setIsLoading(false)
			}
		} else {
			setIsLoggedIn(false);
		}
	}

	useEffect(() => {
		const setAuthAsync = async () => {
			console.log("running");
			if (DEV_USER_ID) {
				console.log("Setting fake authorization user to: ", DEV_USER_ID);
				setAuthHeader({ key: "user_id", value: DEV_USER_ID });
				setIsLoggedIn(true);
				setIsLoading(false);
			} 
		};
		setAuthAsync();
	}, [setAuthHeader]);

	useEffect(() => {
		let unsubscribe: () => void = () => console.log('Dev mode unsubscribe - really dense fn')
		if (!DEV_USER_ID) {
			unsubscribe = onAuthStateChanged(authStateChangeCallback);
		}
		return unsubscribe;
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [])

	const logOut = async () => {
		await AsyncStorage.removeItem("token");
		await handleSignOut();
	};

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

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