import React, { Component } from 'react';
import firebase from 'firebase'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import RegisterScreen from './screens/auth/RegisterScreen';
import LoginScreen from './screens/auth/LoginScreen';
import { firebaseConfig } from './config/firebaseConfig';
import { Text, View } from 'react-native';
import { styles } from './config/styles';

import HomeScreen from './screens/main/Home_page';
import { Provider} from 'react-redux'
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './redux/reducers'
import thunk from 'redux-thunk'


if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig)
}

const store = createStore(rootReducer, applyMiddleware(thunk));

const Stack = createStackNavigator();

export class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      loaded: false,
    }
  }
  
  componentDidMount(){
    firebase.auth().onAuthStateChanged((user) => {
      if (!user){
        this.setState({
          loggedIn: false,
          loaded: true,
        })
      }
      else{
        this.setState({
          loggedIn: true,
          loaded: true,
        })
      }
    })
  }

  render() {

    const { loggedIn, loaded } = this.state

    if(!loaded){
      return(
        <View style={styles.regcontainer}>
          <Text>Hopper</Text>
        </View>
      );
    }

    if(!loggedIn){
      return (
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name={" "} options={{headerShown: false}} component={LoginScreen}/>
            <Stack.Screen name={"Register"} options={{headerTransparent: true, headerTitle: " "}} component={RegisterScreen}/>
          </Stack.Navigator>
        </NavigationContainer>
      );
    }

    return(
      <Provider store={store}>
        <NavigationContainer>
          <Stack.Navigator initialRouteName="Home">
            <Stack.Screen name="Home" component={HomeScreen} />
          </Stack.Navigator>
        </NavigationContainer>
      </Provider>
    );
  }
}

export default App