import React, { createContext, useContext, useEffect, useReducer } from "react";
import { useGroupReducer } from "../useReducer/reducers";
import { AuthContext } from "../../Context/AuthProvider";
import { db } from "../../firebase.js";
import { collection, getDocs, query, where, onSnapshot } from "firebase/firestore";

const initialState = {
  group: undefined,
};

const AppContext = createContext({
  state: initialState,
  dispatch: () => null,
});

const AppProvider = ({ children }) => {
  const { currentUserEmail } = useContext(AuthContext);
  const [appState, appDispatch] = useReducer(useGroupReducer, initialState);

  useEffect(() => {
    if (typeof currentUserEmail === 'undefined') {
      return;
    }
    if (!currentUserEmail) {
      appDispatch({ type: "DELETE_GROUP" });
      return;
    }
    return onSnapshot(
      query(
        collection(db, "users"),
        where("email", "==", currentUserEmail)
      ),
      snapshot => {
        const doc = snapshot.docs[0];
        if (typeof doc === 'undefined') {
          appDispatch({ type: "DELETE_GROUP" });
        } else {
          appDispatch({ type: "CREATE_GROUP", payload: doc.data() });
        }
      }
    );
  }, [currentUserEmail]);

  return (
    <AppContext.Provider value={{ appState, appDispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export { AppContext, AppProvider };
