import React, { useEffect, useState } from 'react';
import { AppState, StatusBar, useColorScheme } from 'react-native';
import { PaperProvider } from 'react-native-paper';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { RealmProvider } from '@realm/react';
import { Provider as ReduxProvider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import type {} from 'redux-thunk/extend-redux';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { lightTheme, darkTheme } from './theme';
import { Meme, Tag } from './database';
import NavigationContainer from './navigation';
import { store, persistor, validateSettings } from './state';
import { LoadingView } from './components';
import { Welcome } from './screens';
import styles from './styles';
import { DimensionsProvider } from './contexts';

const App = () => {
  const [showWelcome, setShowWelcome] = useState(false);
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  const theme = isDarkMode ? darkTheme : lightTheme;

  const onBeforeLift = async () => {
    await store.dispatch(validateSettings());
    const { settings } = store.getState();
    if (!settings.storageUri) {
      setShowWelcome(true);
    }
  };

  useEffect(() => {
    const subscription = AppState.addEventListener('change', async state => {
      if (state !== 'active') return;
      await store.dispatch(validateSettings());
      const { settings } = store.getState();
      if (!settings.storageUri) {
        setShowWelcome(true);
      }
    });
    return () => subscription.remove();
  }, []);

  return (
    <PaperProvider theme={theme}>
      <DimensionsProvider>
        <ReduxProvider store={store}>
          <PersistGate
            loading={<LoadingView />}
            persistor={persistor}
            onBeforeLift={onBeforeLift}>
            <RealmProvider schema={[Meme, Tag]}>
              <GestureHandlerRootView style={styles.flex}>
                <SafeAreaProvider>
                  <StatusBar
                    barStyle={isDarkMode ? 'light-content' : 'dark-content'}
                    backgroundColor={theme.colors.background}
                  />
                  {showWelcome ? (
                    <Welcome onWelcomeComplete={() => setShowWelcome(false)} />
                  ) : (
                    <NavigationContainer />
                  )}
                </SafeAreaProvider>
              </GestureHandlerRootView>
            </RealmProvider>
          </PersistGate>
        </ReduxProvider>
      </DimensionsProvider>
    </PaperProvider>
  );
};

export default App;
