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

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

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

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

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

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

      const userSnap = await usersRef.doc(uid).get();
      const user = userSnap?.data() || {};
      if (userSnap.exists) setCurrentUserData(user);

      const hasUserName = !!user?.userName;
      navigation.reset({
        index: 0,
        routes: [
          {
            name: hasUserName ? Routes.BottomTab : Routes.CreatePseudo,
          },
        ],
      });
    } catch (error) {
      // Pas d'utilisateur connecté => vers Login
      navigation.reset({
        index: 0,
        routes: [
          {
            name: Routes.Login,
          },
        ],
      });
    } finally {
      setIsFullyLoaded(true);
    }
  };

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