import React, {useEffect} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {Provider, useSelector} from 'react-redux';
import {RootState, store} from '@redux/store';
import {appStatus} from '@configs/appNonSaveVar';
import {appNonSaveVarActions} from '@configs/appNonSaveVarReducer';
import {ThemeMode, ThemeType} from '@configs/colors';
import StartHelper from '@pages/appStart/StartHelper';
import {GluestackUIProvider} from '@gluestack-ui/themed';
import configDarkTheme from '@configs/colors';
import Navigation from '@navigation/navigation';
import {MyStatusBar} from '@components/MyStatusBar';
import {SafeAreaView} from 'react-native';
import {appVarActions} from '@configs/appVarReducer';
import {saveVarChanges} from '@helper/appData';

const App = () => {
  useEffect(() => {
    console.log('App opened.');
  }, []);

  return (
    <Provider store={store}>
      <OtherProviders />
    </Provider>
  );
};

const OtherProviders = () => {
  const globalTheme = useSelector(
    (state: RootState) => state.appVariables.preferences.theme,
  );
  const currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );

  const navigationTheme = {
    dark: globalTheme !== ThemeMode.Light,
    colors: {
      // primary: '#ff7d4f',
      background: currentTheme.backgroundDark400, // color of deep screen background
      //card: '#222',
      text: '#fff', // color of header text
      //border: '#ff7d4f',
      //notification: '#fff',
    },
  };

  const themeConfig: ThemeType = configDarkTheme;

  useEffect(() => {
    appNonSaveVarActions.setTheme(themeConfig.tokens);
  });

  return (
    <NavigationContainer theme={navigationTheme}>
      <GluestackUIProvider config={themeConfig}>
        <MainComponent />
      </GluestackUIProvider>
    </NavigationContainer>
  );
};

const MainComponent = () => {
  const currentAppStatus = useSelector(
    (state: RootState) => state.nonSaveVariables.appStatus,
  );

  return (
    <SafeAreaView style={{flex: 1}}>
      <StartHelper />
      <MyStatusBar />
      {currentAppStatus === appStatus.APP_RUNNING ? <Navigation /> : null}
    </SafeAreaView>
  );
};

export default App;
