import { useColorScheme } from "@/hooks/use-color-scheme";
import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider,
} from "@react-navigation/native";
import { Stack, useRouter } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { onAuthStateChanged, User } from "firebase/auth";
import { doc, getDoc } from "firebase/firestore";
import { useEffect, useState } from "react";
import "react-native-reanimated";
import { auth, db } from "../firebase_config";

import { Platform, UIManager } from 'react-native';
import { ChantierProvider } from "./ContextChantier";
import { useUser } from "./ContextUser";
import { RessourcesProvider } from "./ContextRessource";
import LoginScreen from "./login/login";


export const unstable_settings = {
  anchor: "(tabs)",
};

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const { setUser, setRole, user } = useUser();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      if (!currentUser) {
        console.log("No user logged in");
        setUser(null);
        setRole(null);
        setLoading(false);
        return;
      }

      setUser(currentUser);

      const userDocRef = doc(db, "user", currentUser.uid);
      const userDoc = await getDoc(userDocRef);
      console.log("User doc data:", userDoc.data());
      if (!userDoc.exists()) {
        setUser(null);
        setLoading(false);
        return;
      }
      setRole(userDoc.data().role);
      setUser(currentUser);
      setLoading(false);
    });

    return unsubscribe;
  }, []);

  if (loading) {
    return null; // ou un SplashScreen
  }


  return (
      <ChantierProvider>
        <RessourcesProvider>
          <ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>

            {user ? (
              <Stack>
                <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
                <Stack.Screen name="selectChantier" options={{ headerShown: false }} />
                <Stack.Screen
                  name="modal"
                  options={{ presentation: "modal", title: "Modal" }}
                />
              </Stack>
            ) : (
              <LoginScreen />
            )}

            <StatusBar style="auto" />
          </ThemeProvider>
        </RessourcesProvider>
      </ChantierProvider>
  );
}
