import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Alert, Keyboard, Platform } from 'react-native';
import { NavigationActions } from 'react-navigation';
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 } from '~/lib/validate';
import { createConstrains } from '~/lib/validate/preset';
import { Text, color } from 'nixplay-ui-kit';
import { Button } from '~comp';
import { TextInput } from '~comp/reduxForm';

import { color as basicColor } from '~/styles/variables';
import {
	SHOW_TOAST,
	SHOW_TOAST_ERROR,
	UPDATE_REGISTRATION_INFO,
	VERIFY_CODE,
} from '~/store/actionTypes';

import { styles } from './styles';

let currentState = {};

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

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

	constructor(props) {
		super(props);

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

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

		this.props.navigation.setParams({
			onPressBack: this.onBackPress,
		});
	}

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

	onBackPress = () => {
		const { mobileNumber } = this.state;
		const txtToVerify = !_.isEmpty(mobileNumber) ? 'SMS' : 'Email';
		this.showAlert(
			'MAAGApp',
			`Check your ${txtToVerify.toLowerCase()} to get the verification code and continue application.`,
			() => { this.props.navigation.dispatch(NavigationActions.navigate({ routeName: 'OnboardingIntro' })); },
			() => { console.log('CONTINUE'); },
		);
	}

	showAlert = (title, msg, callbackCancel, callbackContinue) => {
		Alert.alert(
			title,
			msg,
			[
				{
					text: i18n.t('common.cancel'),
					onPress: callbackCancel ? () => { callbackCancel(); } :
						() => {},
				},
				{
					text: i18n.t('common.continue'),
					onPress: callbackContinue ? () => { callbackContinue() } :
						() => {},
				},
			],
			{ cancelable: false },
		);
	}

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

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

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

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

	render() {
		const { verificationCode, mobileNumber } = this.state;
		const txtToVerify = !_.isEmpty(mobileNumber) ? 'SMS' : 'Email';
		const titleToVerify = !_.isEmpty(mobileNumber) ? 'Mobile Number' : 'Email';
		return (
			<View style={styles.container}>
				<View style={styles.inputContainer}>
					<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 50 }}>{`${titleToVerify} Verification`}</Text>
					<Text
						style={styles.inputElement}
						textStyle="subhead"
					>
						{`${txtToVerify} Verification Code`}
					</Text>
					<TextInput
						name="verificationCode"
						testID="tiVerificationCode"
						placeholder="8XXXXX"
						autoCapitalize="none"
						autoCorrect={false}
						hideError
						maxLength={6}
						selectionColor={color.wrikeGreen2}
						blurOnSubmit
						onChange={text => {
							this.setState({
								verificationCode: text,
							});
						}}
						onSubmitEditing={this.debouncerHandleSubmit}
						defaultText={verificationCode}
					/>
				</View>
				<View style={styles.checkboxContainer}>
					<View style={styles.checkboxLabel}>
						<Text style={{ color: basicColor.gitlabGray4, paddingHorizontal: 18 }} textStyle="subhead"> </Text>
					</View>
				</View>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.mainText}>
						<Text style={{ color: basicColor.gitlabGray4 }} textStyle="subhead">{`Please check your ${txtToVerify.toLowerCase()} app. See the received MAAGApp sent message.`}</Text>
					</View>
					<View style={styles.buttonContainer}>
						<Button
							testID="verifyCode"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={!this.props.dirty || !this.props.valid}
							text={i18n.t('common.verifyCode')} />
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

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

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const { verificationCode } = values;
		const mobileNumber = _.get(currentState, 'mobileNumber', '');
		const emailAddress = _.get(currentState, 'emailAddress', '');
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					dispatch({
						type: VERIFY_CODE,
						payload: {
							mobileNumber,
							emailAddress,
							code: verificationCode,
							resolve,
							reject,
						},
					});
				} else {
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		if (!_.isEmpty(verificationCode)) {
			dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { verificationCode } });
			callAPI();
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid verification code.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	console.log('onSubmitSuccess: ', result);
	const {
		code, emailAddress, mobileNumber, regType,
	} = currentState;
	console.log('VERIFY>CODE: ', regType);
	if (_.has(result, 'message') && _.isEqual(result.message, 'Match code')) {
		props.navigation.push(
			'SetPassword',
			{
				code, emailAddress, mobileNumber, regType, isVerified: true,
			},
		);
	} else {
		dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Does not match the verification code.' } });
	}
};

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

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

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

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