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 { UserProvider } from "./ContextUser";


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

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const [user, setUser] = useState<User | null>(null);
  const [userRole, setUserRole] = useState<string | null>(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
      if (!currentUser) {
        setUser(null);
        setUserRole(null);
        router.replace("/login/login");
        return;
      }

      const userDocRef = doc(db, "user", currentUser.uid);
      const userDoc = await getDoc(userDocRef);

      if (!userDoc.exists()) {
        router.replace("/login/login");
        setUser(null);
        setUserRole(null);
        return;
      }

      const { role } = userDoc.data();
      setUser(currentUser);
      setUserRole(role);
      router.replace("/(tabs)/home");
    });
    return unsubscribe; 
  }, []);

  return (
    <UserProvider>
      <ChantierProvider>
        <ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
          <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.Screen name="login" options={{ headerShown: false }} />
          </Stack>
          <StatusBar style="auto" />
        </ThemeProvider>
      </ChantierProvider>
    </UserProvider>
  );
}
