import React, { Component } from 'react';
import _ from 'lodash';
import { YellowBox, View, AppState } from 'react-native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from '~/store/store';
import { Root } from '~/navigation';
import { NavigationActions } from 'react-navigation';
import SplashScreen from 'react-native-splash-screen';
import Mixpanel from 'react-native-mixpanel';
import {
	RESET_REQUEST_STATE,
	UPDATE_APP_STATE,
} from '~/store/actionTypes';
import { Toaster, ToasterService } from 'nixplay-ui-kit';

// AppSync Start
import { ApolloProvider } from 'react-apollo';

import { config } from '~/config';

// https://github.com/react-navigation/react-navigation/issues/3956#issuecomment-380648083
YellowBox.ignoreWarnings([
	'Warning: isMounted(...) is deprecated',
	'Module RCTImageLoader',
	'Module RNFetchBlob requires main queue setup since it overrides',
	'Module RCTImageLoader requires main queue setup since it overrides',
	'Module RCTImagePickerManager requires main queue setup since it overrides',
	'Module RNSafeArea requires main queue setup since it overrides ',
	'Module ReactNativeShareExtension requires main queue setup since it overrides',
	'Module RNGoogleSignin requires main queue setup since it over\ides',
	'RNReactNativeHapticFeedback is not available',
	'Class RCTCxxModule',
	// supress rectjs major deprecated warning, MUST resolve it in the near future
	'Warning: componentWillReceiveProps',
	'Warning: componentWillMount',
]);

export default class App extends Component {
	constructor(props) {
		super(props);
		// firebase.crashlytics().enableCrashlyticsCollection();
		// remove me if not login
		// if (__DEV__) DefaultPreference.clearAll().then(() => {});
		this.state = {
			friendsBadged: false,
			photosBadged: false,
			moreBadged: false,
			uploadTotal: 0,
			elapsed: 0,
			previousScreen: '',
			currentScreen: '',
			isConnected: true,
			previousNavRoot: '',
			hasUser: false,
		};
		// pushNotifications.configure();
		this.handleAppStateChange = this.handleAppStateChange.bind(this);
		this.currentRoot = '';
		this.client = {};
		// Current device language
		// console.log('locales', RNLocalize.getLocales());
		// User preferred languages (in order)
		// console.log('locales', RNLocalize.getLocales());
		// this.debouncerSwitchRoot = _.debounce(this.switchRoot, 100, {
		// 	leading: true,
		// 	trailing: false,
		// });
		const mxToken = (config.IS_DEBUG) ? '5abbc4ceb43eda28f17b05179749caf9' : 'b16233ccc93e4b1a6d9863bb269b70af';
		Mixpanel.sharedInstanceWithToken(mxToken);
	}

	componentDidMount() {
		store.subscribe(this.onStoreUpdate.bind(this));
		AppState.addEventListener('change', this.handleAppStateChange);
		SplashScreen.hide();
	}

	componentWillUnmount() {
		AppState.removeEventListener('change', this.handleAppStateChange);
	}

	onRehydrate = async () => {
		store.dispatch({ type: RESET_REQUEST_STATE });
	}

	onStoreUpdate() {
		const {
			root,
		} = store.getState().app;

		if (this.currentRoot !== root) {
			this.currentRoot = root;
		}

		const {
			network,
		} = store.getState();

		this.switchRoot();
		const enabledBottomNotification = false;

		this.setState({
			bottomNotificationTheme: network.isConnected ? 'normal' : 'alert',
			enabledBottomNotification,
			// uploadTotal: network.isConnected ? _.size(items) : 0,
			// message: this.getBottomNotificationMessage(network, meta.elapsed, _.size(items)),
			// linkMessage: network.isConnected && _.size(items) > 0
			// 	? ` ${i18n.t('common.viewProgress')}`
			// 	: '',
			// elapsed: network.isConnected ? (meta.elapsed || 0) : 0,
			isConnected: network.isConnected,
		});
	}

	switchRoot = () => {
		const { users } = store.getState();
		// console.log('beneficiaries: ', beneficiaries.scannedUsers);
		if (this.navigation) {
			if (!_.isEqual(this.state.previousNavRoot, this.currentRoot)) {
				// console.log('EMPTY SCREEN');
				if (this.currentRoot === 'main' || this.state.hasUser || !_.isEmpty(users.currentUser)) {
					// console.log('LOGGED USER 1');
					const { currentUser } = users;
					this.setState({ hasUser: true, previousNavRoot: this.currentRoot });
					if (parseInt(currentUser.regType, 0) === 5) {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'SWTeacherDashboard' }));
					} else if (parseInt(currentUser.regType, 0) === 4) {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'SWValidatorDashboard' }));
					} else if (parseInt(currentUser.regType, 0) === 3) {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'SWAssessorDashboard' }));
					} else if (parseInt(currentUser.regType, 0) === 2) {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'SocialWorkerDashboard' }));
					} else if (parseInt(currentUser.regType, 0) === 1) {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'BasicUserDashboard' }));
					} else {
						this.navigation.dispatch(NavigationActions.navigate({ routeName: 'NonAuthedFlow' }));
					}
				} else {
					this.setState({ previousNavRoot: this.currentRoot });
					// console.log('NonAuthedFlow');
					this.navigation.dispatch(NavigationActions.navigate({ routeName: 'NonAuthedFlow' }));
				}
			}
		}
	}

	handleAppStateChange = (nextAppState) => {
		store.dispatch({ type: UPDATE_APP_STATE, payload: nextAppState });
	}

	render() {
		return (
			<ApolloProvider client={this.client}>
				<Provider store={store}>
					<View style={{ flex: 1, position: 'relative' }}>
						<PersistGate
							persistor={persistor}
							onBeforeLift={this.onRehydrate}
						>
							<Root
								ref={(nav) => { this.navigation = nav; }}
								onNavigationStateChange={() => {}}
								screenProps={{
									gqlClient: this.client,
									friendsBadged: this.state.friendsBadged,
									photosBadged: this.state.photosBadged,
									moreBadged: this.state.moreBadged,
									enabled: this.state.enabledBottomNotification,
									uploadTotal: this.state.uploadTotal,
									elapsed: this.state.elapsed,
									theme: this.state.bottomNotificationTheme,
									progressMessage: this.state.message,
									linkMessage: this.state.linkMessage,
									previousScreen: this.state.previousScreen,
									currentScreen: this.state.currentScreen,
									isConnected: this.state.isConnected,
									currentRoot: this.state.currentRoot,
								}}
							/>
							<Toaster ref={(toaster) => { ToasterService.setGlobalToaster(toaster); }} />
						</PersistGate>
					</View>
				</Provider>
			</ApolloProvider>
		);
	}
}
