/* eslint-disable react/display-name */
import { useDataFromRef } from "react-native-minuit/src/hooks";
import useMinuit from "react-native-minuit/src/hooks/useMinuit";
import { createContext, useContext, useGlobal } from "reactn";

import { usersRef } from "../config/firebase";

export const UserDataContext = createContext();

export default ({ children }) => {
  const { setIsLoading, setTooltip } = useMinuit();

  const [currentUID] = useGlobal("currentUID");
  const [currentUserData, setCurrentUserData] = useGlobal("currentUserData");
  const [currentUserRoles] = useGlobal("currentUserRoles");

  useDataFromRef({
    ref: currentUID ? usersRef.doc(currentUID) : null,
    simpleRef: true,
    listener: true,
    condition: currentUID,
    refreshArray: [currentUID],
    onUpdate: (data) => {
      if (data) {
        setCurrentUserData(data);
      } else {
        setCurrentUserData(null);
      }
    },
  });

  return (
    <UserDataContext.Provider value={{}}>{children}</UserDataContext.Provider>
  );
};

export const useUserData = () => {
  return useContext(UserDataContext);
};

// Convenience alias returning the same context, as requested
export const useUser = () => {
  return useContext(UserDataContext);
};
