import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard, Platform } 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 i18n from '~/locale/i18n';
import { validator, isValidMobile } from '~/lib/validate';
import { createConstrains } from '~/lib/validate/preset';
import { Text } from 'nixplay-ui-kit';
import { Button } from '~comp';
import { TextInput } from '~comp/reduxForm';
import { FIRST_TIME_INSTALL } from '~/lib/appConstants';

import { SHOW_TOAST_ERROR, UPDATE_REGISTRATION_INFO } from '~/store/actionTypes';

import { color } from '~/styles/variables';

import { styles } from './styles';

const currentState = {};

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.isRequired,
		valid: PropTypes.bool.isRequired,
		submitting: PropTypes.bool.isRequired,
		submitFailed: PropTypes.bool.isRequired,
		dirty: PropTypes.bool.isRequired,
		error: PropTypes.bool,
	}

	constructor(props) {
		super(props);

		this.state = {
			mobileNumber: '+63',
			bottomOpacity: 1,
		};

		DefaultPreference.set(FIRST_TIME_INSTALL, '')
		this.goToWebView = this.goToWebView.bind(this);

		this.debouncerHandleSubmit = _.debounce(this.props.handleSubmit, 3000, {
			leading: true,
			trailing: false,
		});
	}

	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();
	}

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

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

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

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

	goToWebView(url) {
		this.props.navigation.push('WebView', { webViewUrl: url });
	}

	render() {
		const { mobileNumber } = this.state;
		return (
			<View style={styles.container}>
				{/* <View style={styles.mainText}>
					<Text textStyle="title3" style={{ justifyContent: 'center' }}>Join MAAGApp</Text>
				</View> */}
				<View style={styles.inputContainer}>
					<Text textStyle="title3" style={{ textAlign: 'center', marginBottom: 50 }}>Join MAAGApp</Text>
					<Text
						style={styles.inputElement}
						textStyle="subhead"
					>
						Enter Mobile Number
					</Text>
					<TextInput
						name="mobileNumber"
						testID="tiMobileNumber"
						placeholder="+639XXXXXXXXX"
						autoCapitalize="none"
						autoCorrect={false}
						hideError
						maxLength={13}
						selectionColor={color.wrikeGreen2}
						onChange={text => {
							const trimString = text.trim();
							const mobile = (text.indexOf('+63') === 0) ? trimString : '+63';
							this.setState({
								mobileNumber: mobile,
							});
						}}
						defaultText={mobileNumber}
						blurOnSubmit
						onSubmitEditing={this.debouncerHandleSubmit}
					/>
				</View>
				<View style={styles.checkboxContainer}>
					<View style={styles.checkboxLabel}>
						{i18n.tWithComponent(
							'users.acceptTnc',
							null,
							[
								(text) => (<Text key={text} textStyle="subhead" style={[styles.checkboxLabelLink, { color: color.gitlabGray4 }]} onPress={() => { this.goToWebView('https://www.apple.com'); }}>{text}</Text>),
								(text) => (<Text key={text} textStyle="subhead" style={[styles.checkboxLabelLink, { color: color.gitlabGray4 }]} onPress={() => { this.goToWebView('https://www.google.com'); }}>{text}</Text>),
							],
							(text) => (<Text style={{ color: color.gitlabGray4 }} key={text} textStyle="subhead">{text}</Text>),
						)}
					</View>
				</View>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.mainText}>
						<Text style={{ color: color.gitlabGray4 }} textStyle="subhead"> </Text>
					</View>
					<View style={styles.buttonContainer}>
						<Button
							testID="Next"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={!this.props.dirty || !this.props.valid}
							text={i18n.t('common.next')}
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const validate = (values) => {
	const constraints = createConstrains(['mobileNumber']);
	const errors = validator({
		mobileNumber: values.mobileNumber,
	}, constraints);
	currentState.mobileNumber = values.mobileNumber;
	currentState.gotError = 0;
	return errors;
};

const onSubmit = (values, dispatch, ownProps) => (
	new Promise((resolve, reject) => {
		const { mobileNumber } = values;
		if (isValidMobile(mobileNumber)) {
			// API REQUEST and update db
			console.log('onSubmit');
			dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { mobileNumber } });
			resolve();
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid mobile number.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	console.log('onSubmitSuccess: ', props);
	checkInternetConnection().then(isConnected => {
		console.log('isConnected: ', isConnected);
		// if (isConnected) {
		// 	// if has network
		// 	props.navigation.push('VerifyMobileNumber');
		// } else {
		// if not proceed to set password and update later
		props.navigation.push('SetPassword');
		// }
	});
};

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

const mapActionsToProps = () => ({ });

const FormContainer = reduxForm({
	form: 'SignUpStep1',
	validate,
	onSubmit,
	onSubmitSuccess,
	destroyOnUnmount: false,
})(SignUpStep1);

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