import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, StyleSheet, Platform, Image, Keyboard, Alert } from 'react-native';
import DefaultPreference from 'react-native-default-preference';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { checkInternetConnection } from 'react-native-offline';
import { Button, Text } from 'nixplay-ui-kit';
import Geolocation from '@react-native-community/geolocation';
import OpenAppSettings from 'react-native-app-settings';
import Mixpanel from 'react-native-mixpanel';
import { TextInput } from '~comp/reduxForm';

import i18n from '~/locale/i18n';
import { FIRST_TIME_INSTALL } from '~/lib/appConstants';
import { color as basicColor } from '~/styles/variables';
import MaagapIcon from '~/images/other/maagap';
import { SHOW_TOAST, SHOW_TOAST_ERROR, CHANGE_APP_ROOT, REQUEST_LOGIN, UPDATE_LOCATION_COORDINATES } from '~/store/actionTypes';

import ImageBG from '~/images/onboarding/bg-hero-1366.jpg';

// let currentState = {};
const isAndroid = Platform.OS !== 'ios';


export const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: 'white',
	},
	slideContainer: {
		flex: 1,
	},
	image: {
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
	},
	textContainer: {
		flex: 1,
		justifyContent: 'center',
		paddingHorizontal: 36,
	},
	textTitle: {
		fontSize: 27,
		marginTop: 21,
		marginBottom: 16,
	},
	safeArea: {
		position: 'absolute',
		bottom: 0,
		width: '100%',
	},
	buttonContainer: {
		flexDirection: 'column',
		paddingHorizontal: 18,
		paddingTop: 25,
		paddingBottom: 14,
	},
	button: {
		borderRadius: 4,
	},
	signupButton: {
		marginRight: 0,
		backgroundColor: basicColor.wrikeGreen2,
	},
	loginButton: {
		marginTop: 8,
		backgroundColor: basicColor.wrikeBg,
	},
	pagerDots: {
		flexDirection: 'row',
		justifyContent: 'center',
	},
	dots: {
		width: 8,
		height: 8,
		borderRadius: 4,
		marginHorizontal: 4,
	},
	mainBg: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
	},
	mainText: {
		flex: 1,
		flexDirection: 'column',
		justifyContent: 'flex-start',
		paddingHorizontal: 18,
		marginTop: 56,
	},
	mainTagline: {
		flex: 0.4,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
	},
	inputContainer: {
		paddingLeft: 20,
		paddingRight: 20,
		paddingBottom: 12,
	},
	appIcon: {
		width: 100,
		height: 100,
		alignSelf: 'center',
		marginTop: 0,
		marginBottom: 15,
		opacity: 0.9,
	},
	imageBg: {
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
	},
});


export class OnboardingIntro extends Component {
	static navigationOptions = () => {
		const leftButtons = [];
		const rightButtons = [];
		return {
			headerTransparent: true,
			title: '',
			subtitle: '',
			hideBackButton: true,
			leftButtons,
			rightButtons,
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.isRequired,
		updateLocation: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);

		this.state = {
			username: '',
			password: '',
			bottomOpacity: 1,
		};

		DefaultPreference.set(FIRST_TIME_INSTALL, '');
		this.debouncerHandleSubmit = _.debounce(this.props.handleSubmit, 3000, {
			leading: true,
			trailing: false,
		});
		this.didFocusSubscription = props.navigation.addListener('didFocus', this.getLocation);
	}

	async componentDidMount() {
		if (Platform.OS === 'ios') {
			this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
			this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
		} else {
			this.keyboardWillShowSub = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow);
			this.keyboardWillHideSub = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide);
		}
	}

	componentWillUnmount() {
		this.keyboardWillShowSub.remove();
		this.keyboardWillHideSub.remove();
		if (!_.isEmpty(this.didFocusSubscription)) this.didFocusSubscription.remove();
	}

	getLocation = () => {
		setTimeout(() => {
			if (!_.isEmpty(Geolocation)) {
				// ios
				Geolocation.getCurrentPosition(
					position => {
						const coordinates = JSON.stringify(position);
						this.props.updateLocation(coordinates);
					},
					(error) => {
						if (error.code === 1) {
							Alert.alert(
								'MAAGApp - Location',
								'Please Turn On and Allow your device Location Services for MAAGApp.',
								[
									{ text: i18n.t('common.cancel'), onPress: () => {}, style: 'cancel' },
									{
										text: 'Settings',
										onPress: () => {
											OpenAppSettings.open();
										},
									},
								],
								{ cancelable: false },
							);
						} else if (error.code === 2) {
							Alert.alert(
								'MAAGApp - Location',
								'Please Turn On your device Location Services for MAAGApp.',
								[
									{ text: i18n.t('common.cancel'), onPress: () => {}, style: 'cancel' },
									{
										text: 'Thank you',
										onPress: () => {},
									},
								],
								{ cancelable: false },
							);
						} else {
							// android
							Geolocation.watchPosition(position => {
								const coordinates = JSON.stringify(position);
								this.props.updateLocation(coordinates);
								// Alert.alert(
								// 	'MAAGApp - Location',
								// 	`Current location: ${coordinates}`,
								// 	[
								// 		{
								// 			text: 'OK',
								// 			onPress: () => { },
								// 		},
								// 	],
								// 	{ cancelable: false },
								// );
							});
						}
					},
					{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
				);
			}
		}, 1000);
	}

	keyboardWillShow = () => {
		this.setState({ bottomOpacity: 0 });
	};

	keyboardWillHide = () => {
		this.setState({ bottomOpacity: 1 });
	};

	keyboardDidShow = () => {
		this.setState({ bottomOpacity: 0 });
	};

	keyboardDidHide = () => {
		this.setState({ bottomOpacity: 1 });
	};

	registerType = (regType) => {
		this.props.navigation.push('Registration', { regType });
	}

	render() {
		const { username, password } = this.state;
		return (
			<View style={styles.container}>
				<Image
					source={ImageBG}
					style={styles.imageBg}
					resizeMode="cover"
				/>
				<View style={styles.mainText}>
					<View style={styles.appIcon}>
						<MaagapIcon />
					</View>
					<View style={styles.inputContainer}>
						<TextInput
							name="username"
							testID="tiUsername"
							placeholder="email address or mobile number"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, backgroundColor: 'transparent' }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={username}
							onChange={text => this.setState({
								username: text,
							})}
						/>
						<TextInput
							name="password"
							testID="tiPassword"
							placeholder="password"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							secureTextEntry
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, backgroundColor: 'transparent' }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={password}
							onChange={text => this.setState({
								password: text,
							})}
						/>
						<View style={{ alignSelf: 'center', marginTop: 100 }}>
							<Text color={basicColor.gray}>{i18n.t('users.briefMessage')}</Text>
						</View>
					</View>
				</View>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.buttonContainer}>
						<Button
							testID="SignUp"
							style={[styles.button, styles.signupButton]}
							type="secondary"
							color="white"
							block
							onPress={() => { this.registerType(2); }}
						>
							<Button.Text>{i18n.t('users.signUp')}</Button.Text>
						</Button>
						<Button
							testID="Login"
							style={[styles.button, styles.loginButton]}
							type="secondary"
							color="white"
							block
							onPress={this.debouncerHandleSubmit}
						>
							<Button.Text>{i18n.t('users.login')}</Button.Text>
						</Button>
					</View>
				</SafeAreaView>
				{/* <ActionSheet
					ref={(actionSheet) => { this.contentActionSheet = actionSheet; }}
				>
					<ActionSheet.Action onPress={() => { this.registerType(1); }} testID="Beneficiary">Register as Beneficiary</ActionSheet.Action>
					<ActionSheet.Action onPress={() => { this.registerType(2); }} testID="SW">Social Worker</ActionSheet.Action>
					<ActionSheet.Action onPress={() => { this.registerType(3); }} testID="SWA">SW - Assessor</ActionSheet.Action>
					<ActionSheet.Action onPress={() => { this.registerType(4); }} testID="SWV">SW - Validator</ActionSheet.Action>
					<ActionSheet.Action onPress={() => { this.registerType(5); }} testID="SWT">SW - Teacher</ActionSheet.Action>
					<ActionSheet.Cancel testID="Cancel">{i18n.t('common.close')}</ActionSheet.Cancel>
				</ActionSheet> */}
			</View>
		);
	}
}

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const username = _.get(values, 'username', '');
		const password = _.get(values, 'password', '');
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					Mixpanel.trackWithProperties('try_login', { username });
					// console.log('username: ', username, password);
					dispatch({
						type: REQUEST_LOGIN,
						payload: {
							username,
							password,
							resolve,
							reject,
						},
					});
				} else {
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		if (!_.isEmpty(username) && !_.isEmpty(password)) {
			if (username.length >= 6 && password.length >= 6) {
				callAPI();
			} else {
				dispatch({ type: SHOW_TOAST, payload: { text: 'Verify your username or password length.' } });
				reject();
			}
		} else {
			dispatch({ type: SHOW_TOAST, payload: { text: 'Some fields are required.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch) => {
	if (_.has(result, 'status')) {
		dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid username or password.' } });
	} else {
		dispatch({
			type: CHANGE_APP_ROOT,
			payload: { root: 'main' },
		});
	}
};

const mapStateToProps = (state) => ({
	isLoggedIn: !_.isEmpty(state.user.token),
	languageCode: _.get(state, 'settings.languageCode'),
});

const mapActionsToProps = (dispatch) => ({
	updateLocation(payload) {
		dispatch({ type: UPDATE_LOCATION_COORDINATES, payload });
	},
});

const FormContainer = reduxForm({
	form: 'OnboardingIntro',
	onSubmit,
	onSubmitSuccess,
	destroyOnUnmount: true,
})(OnboardingIntro);

export default connect(mapStateToProps, mapActionsToProps)(FormContainer);
