import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard, Platform } from 'react-native';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';

import i18n from '~/locale/i18n';
import { validator } 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 { color as basicColor } from '~/styles/variables';
import { SHOW_TOAST_ERROR, UPDATE_REGISTRATION_INFO } from '~/store/actionTypes';
import { styles } from './styles';

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

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		registration: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.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');
		const isVerified = props.navigation.getParam('isVerified', false);
		currentState = {
			...currentState, emailAddress, mobileNumber, regType, code, isVerified,
		};
		this.state = {
			bottomOpacity: 1,
		};

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

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

	goToNext = () => {
		this.props.navigation.push('SetBasicInformation');
	}

	render() {
		const { password } = this.state;
		const hasError = (!_.isEmpty(currentState.gotError));
		const colorTxt = (hasError && (_.isEqual(currentState.gotError[0], 'Must contain set characters'))) ? basicColor.red : basicColor.gitlabGray4;
		return (
			<View style={styles.container}>
				<View style={styles.inputContainer}>
					<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 50 }}>Set Security</Text>
					<Text
						style={styles.inputElement}
						textStyle="subhead"
					>
						Enter Password
					</Text>
					<TextInput
						name="password"
						testID="tiPassword"
						placeholder={i18n.t('users.password')}
						autoCapitalize="none"
						autoCorrect={false}
						secureTextEntry
						returnKeyType="next"
						maxLength={32}
						keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
						blurOnSubmit
						style={{ color: basicColor.wrikeBg }}
						selectionColor={basicColor.wrikeGreen2}
						onChange={text => {
							this.setState({
								password: text
							})
						}}
						onSubmitEditing={this.debouncerHandleSubmit}
						defaultText={password}

					/>
				</View>
				<View style={styles.checkboxContainer}>
					<View style={styles.checkboxLabel}>
						<Text style={{ color: colorTxt, paddingHorizontal: 18 }} textStyle="subhead">Your password must have at least 8 combined letters, numbers, symbols (like ! and %).</Text>
					</View>
				</View>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.mainText}>
						<Text style={{ color: basicColor.gitlabGray4 }} textStyle="subhead"> </Text>
					</View>
					<View style={styles.buttonContainer}>
						<Button
							testID="Next"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={hasError}
							text={i18n.t('common.next')}
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const validate = (values) => {
	const constraints = createConstrains(['myPassword']);
	const errors = validator({
		myPassword: values.password,
	}, constraints);
	currentState.password = values.password;
	currentState.gotError = (_.isEmpty(errors)) ? '' : errors.myPassword;
	return errors;
};

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const { password } = values;
		if (!_.isEmpty(password) && password.length >= 8) {
			// API REQUEST to validate and update DB
			dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { password } });
			console.log('onSubmit>Valid: ', password);
			resolve(password);
		} else {
			console.log('onSubmit: ', password);
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Invalid password.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	console.log('onSubmitSuccess: ', props);
	// switch route for standard user and social worker
	const {
		code, emailAddress, mobileNumber, regType,
	} = currentState;
	console.log('PASS: ', regType);
	if (parseInt(regType, 0) === 1) {
		props.navigation.push(
			'RegisterBeneficiary',
			{
				code, emailAddress, mobileNumber, regType, isVerified: true, password: result,
			},
		);
	} else {
		props.navigation.push(
			'SetBasicInformation',
			{
				code, emailAddress, mobileNumber, regType, isVerified: true, password: result,
			},
		);
	}
};


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

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

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

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