import React, {useState, useEffect, Fragment} from 'react';

import {NativeBaseProvider} from 'native-base';
import {NavigationContainer} from '@react-navigation/native';

import {getBackgroundColor, theme, ThemeSwitcher} from '@caj/configs/colors';

import StatusBar from './StatusBar';
import Navigation, {linking} from './caj/Navigation';

import {Provider, useSelector} from 'react-redux';
import {RootState, store} from '@caj/redux/store';
import StartHelper from './appStart/StartHelper';
import {appStatus} from '@caj/configs/appNonSaveVar';
import {ThemeMode} from '@caj/configs/appVar';

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 navigationTheme = {
    dark: globalTheme !== ThemeMode.Light,
    colors: {
      primary: '#ff7d4f',
      background: getBackgroundColor(globalTheme),
      card: '#222',
      text: '#fff',
      border: '#ff7d4f',
      notification: '#fff',
    },
  };

  return (
    <NavigationContainer theme={navigationTheme} /*linking={linking}*/>
      <NativeBaseProvider theme={theme(globalTheme)}>
        <MainComponent />
      </NativeBaseProvider>
    </NavigationContainer>
  );
};

const MainComponent = () => {
  const currentAppStatus = useSelector(
    (state: RootState) => state.nonSaveVariables.appStatus,
  );
  return (
    <Fragment>
      <StartHelper />
      <ThemeSwitcher />
      <StatusBar />
      {currentAppStatus === appStatus.APP_RUNNING ? <Navigation /> : null}
    </Fragment>
  );
};

export default App;
