import React, { useEffect, useContext } from "reactn";
import { View } from "react-native";

import firebase, { usersRef } from "../config/firebase";
import { Routes } from "../navigation";

import { SplashAnimationContext } from "../providers/SplashAnimationProvider";
import { UserDataContext } from "../providers/UserDataProvider";

import { isDesktop, isWeb } from "../hooks/useLayoutType";

export default ({ navigation }) => {
  const { setCurrentUserData } = useContext(UserDataContext);
  const { setIsFullyLoaded } = useContext(SplashAnimationContext);

  useEffect(() => {
    userRouting();
  }, []);

  const userRouting = async () => {
    try {
      if (!firebase.auth().currentUser?.uid) {
        throw new Error("No user");
      }

      const userDoc = await usersRef
        .doc(firebase.auth().currentUser?.uid)
        .get();

      if (userDoc?.data()) {
        setCurrentUserData(userDoc.data());

        navigation.reset({
          index: 0,
          routes: [
            {
              name: Routes.BottomTab,
              params: {
                screen: Routes.Home,
              },
            },
          ],
        });
      } else {
        throw new Error("No data");
      }
    } catch (error) {
      console.log(error);

      navigation.reset({
        index: 0,
        routes: [
          {
            name: Routes.Onboarding,
          },
        ],
      });
    } finally {
      setIsFullyLoaded(true);
    }
  };

  return <View style={{ flex: 1 }}></View>;
};
