import React, { createContext, useContext, useEffect, useState } from "react";
import auth, { FirebaseAuthTypes } from "@react-native-firebase/auth";
import { useRouter } from "expo-router";

interface LoginState {
  tempEmail?: string;
  passwordReset?: boolean
}

const AuthContext = createContext<
  [
    FirebaseAuthTypes.User | null,
    LoginState | null,
    React.Dispatch<React.SetStateAction<LoginState | null>> | null,
    boolean
  ]
>([null, null, null, false]);

export default function AuthProvider(props: { children: React.ReactNode }) {
  const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null);
  const [init, setInit] = useState(true);
  const [loginstate, setLogInState] = useState<LoginState|null>(null);
  useEffect(() => {
    const subscriber = auth().onAuthStateChanged((u) => {
      setUser(u);
      if (init) {
        setInit(false);
      }
      return subscriber;
    });
  }, []);
  if (init) return null;
  return (
    <AuthContext.Provider value={[user, loginstate, setLogInState, init]}>
      {props.children}
    </AuthContext.Provider>
  );
}

export function useAuthState() {
  return useContext(AuthContext);
}
