import React, { useEffect, useState } from 'react';
import {
  AppState,
  StatusBar,
  useColorScheme,
  StyleSheet,
  UIManager,
} 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';

const appStyles = StyleSheet.create({
  gestureHandler: {
    flex: 1,
  },
});

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

  const onBeforeLift = async () => {
    UIManager.setLayoutAnimationEnabledExperimental(true);
    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 (
    <ReduxProvider store={store}>
      <RealmProvider schema={[Meme, Tag]}>
        <PaperProvider theme={theme}>
          <PersistGate
            loading={<LoadingView />}
            persistor={persistor}
            onBeforeLift={onBeforeLift}>
            <GestureHandlerRootView style={appStyles.gestureHandler}>
              <SafeAreaProvider>
                <StatusBar
                  barStyle={isDarkMode ? 'light-content' : 'dark-content'}
                  backgroundColor={theme.colors.background}
                />
                {showWelcome ? (
                  <Welcome onWelcomeComplete={() => setShowWelcome(false)} />
                ) : (
                  <NavigationContainer />
                )}
              </SafeAreaProvider>
            </GestureHandlerRootView>
          </PersistGate>
        </PaperProvider>
      </RealmProvider>
    </ReduxProvider>
  );
};

export default App;
