import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard, Platform, ScrollView } from 'react-native';
import DeviceInfo from 'react-native-device-info';
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 { isValidMobile, isValidEmail } from '~/lib/validate';
import { Text } from 'nixplay-ui-kit';
import { Button } from '~comp';
import { TextInput, Switch } from '~comp/reduxForm';

import {
	SHOW_TOAST_ERROR,
	SHOW_TOAST,
	REQUEST_VERIFICATION,
	RESET_ALL_USERS,
} from '~/store/actionTypes';

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

import { styles } from './styles';

let currentState = {};

export class Registration 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,
		// resetAllUsers: PropTypes.func.isRequired,
		// error: PropTypes.bool,
	}

	constructor(props) {
		super(props);

		const regType = props.navigation.getParam('regType', '1');
		console.log('regType: ', regType);
		currentState = { ...currentState, regType, agreement: false };
		this.state = {
			mobileNumber: '',
			emailAddress: '',
			bottomOpacity: 1,
		};

		this.goToWebView = this.goToWebView.bind(this);

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

	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, emailAddress } = this.state;
		return (
			<View style={styles.container}>
				<ScrollView
					style={{
						flex: 1,
					}}
					contentContainerStyle={styles.contentContainer}
					showsVerticalScrollIndicator={false}
					showsHorizontalScrollIndicator={false}
				>
					<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 => { this.setState({ mobileNumber: text }); }}
							onFocus={() => { if (_.isEmpty(mobileNumber)) { this.setState({ mobileNumber: '+63' }); } }}
							defaultText={mobileNumber}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
						/>
					</View>
					<View style={styles.delimeter}>
						<View style={[styles.delimeterLine, { marginLeft: 20 }]} />
						<Text textStyle="subhead" style={styles.delimeterText}>OR</Text>
						<View style={[styles.delimeterLine, { marginRight: 20 }]} />
					</View>
					<View style={styles.inputContainer}>
						<Text
							style={styles.inputElement}
							textStyle="subhead"
						>
							Enter Email Address
						</Text>
						<TextInput
							name="emailAddress"
							testID="tiEmailAddress"
							placeholder=""
							autoCapitalize="none"
							autoCorrect={false}
							hideError
							maxLength={64}
							selectionColor={color.wrikeGreen2}
							defaultText={emailAddress}
							onChange={text => this.setState({ emailAddress: text })}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
						/>
					</View>
					<View style={styles.inputContainer}>
						<Text textStyle="subhead">{i18n.tWithComponent('users.paalala')}</Text>
						<Text
							style={[styles.inputElement, { marginTop: 10 }]}
							textStyle="subhead"
						>
							Ako ay sumasang-ayon:
						</Text>
						<Switch
							name="slideshow.shuffle"
							testID="SlideshowShuffle"
							value={currentState.agreement}
							onChange={(status) => {
								currentState = { ...currentState, agreement: status };
							}}
						/>
					</View>
					{/* <View style={[styles.checkboxContainer, { marginBottom: 300 }]}>
						<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> */}
				</ScrollView>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.buttonContainer}>
						<Button
							testID="Next"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={!this.props.dirty}
							text={i18n.t('common.next')}
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const mobileNumber = _.get(values, 'mobileNumber', '');
		const emailAddress = _.get(values, 'emailAddress', '');
		currentState = { ...currentState, mobileNumber, emailAddress };
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					dispatch({
						type: REQUEST_VERIFICATION,
						payload: {
							mobileNumber,
							emailAddress,
							deviceId: '',
							deviceOS: DeviceInfo.getModel(),
							resolve,
							reject,
						},
					});
				} else {
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		// console.log('onSubmit', isValidMobile(mobileNumber), isValidEmail(emailAddress));
		if (!_.isEmpty(mobileNumber)) {
			if (isValidMobile(mobileNumber)) {
				if (currentState.agreement === true) {
					callAPI();
				} else {
					dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Need to accept the terms and condition.' } });
					reject();
				}
				// dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { mobileNumber } });
			} else {
				// console.log('ERROR: ', values);
				dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid mobile number.' } });
				reject();
			}
		} else if (!_.isEmpty(emailAddress)) {
			if (isValidEmail(emailAddress)) {
				if (currentState.agreement === true) {
					callAPI();
				} else {
					dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Need to accept the terms and condition.' } });
					reject();
				}
				// callAPI();
				// dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { emailAddress } });
			} else {
				// console.log('ERROR: ', values);
				dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid email address.' } });
				reject();
			}
		} else {
			// console.log('ERROR: ', values);
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid mobile number or email address.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	const { regType } = currentState;
	// console.log('onSubmitSuccess: ', result, regType);
	if (_.isEqual(result.status, 201)) {
		const emailAddress = _.get(currentState, 'emailAddress', 'null');
		const mobileNumber = _.get(currentState, 'mobileNumber', 'null');
		props.navigation.push(
			'VerifyMobileNumber',
			{
				code: result.code,
				raw: result,
				emailAddress,
				mobileNumber,
				regType,
			},
		);
	} else {
		// invalid
		dispatch({ type: SHOW_TOAST_ERROR, payload: { text: result.message } });
	}
	// props.navigation.push('VerifyMobileNumber', { result });
	// 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
	// 	// }
	// });
};

const onSubmitFail = () => { };

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

const mapActionsToProps = (dispatch) => ({
	resetAllUsers() {
		dispatch({ type: RESET_ALL_USERS, payload: {} });
	},
});

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

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