import React, { Component } from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
import {
	View,
	Platform,
	Keyboard,
} from 'react-native';
import {
	Text,
	Button,
	ButtonGroup,
	ToasterService,
} from 'nixplay-ui-kit';
import { reduxForm } from 'redux-form';
import {
	TextInput,
} from '~comp/reduxForm';
import i18n from '~/locale/i18n';
import { validator } from '~/lib/validate';
import OfflineNotificationBar from '~comp/offlineNotificationBar';
import { connect } from 'react-redux';

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

import {
	analytics,
	debounceWrapper,
} from '~/lib/utils';
import { styles } from './styles';

const ButtonEx = debounceWrapper(Button);

export class ChangePassword extends Component {
	static navigationOptions = () => ({
		title: i18n.t('users.changePasswordTitle'),
		// onPressBack: () => navigation.getParam('onPressBack', () => analytics.logAction('header_null_tapped'))(),
	})

	static propTypes = {
		handleSubmit: PropTypes.func.isRequired,
		isConnected: PropTypes.bool.isRequired,
		languageCode: PropTypes.string.isRequired,
		valid: PropTypes.bool,
	}

	static defaultProps = {
		valid: true,
	}

	componentDidMount() {
		if (Platform.OS !== 'ios') {
			Keyboard.addListener('keyboardDidShow', this.keyboardDidShow);
		} else {
			Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
		}
	}

	shouldComponentUpdate(nextProps) {
		if (!_.isEqual(this.props.isConnected, nextProps.isConnected) ||
			!_.isEqual(this.props.languageCode, nextProps.languageCode) ||
			!_.isEqual(this.props.valid, nextProps.valid)) {
			return true;
		}
		return false;
	}

	componentWillUnmount() {
		if (Platform.OS !== 'ios') {
			Keyboard.removeListener('keyboardDidShow', this.keyboardDidShow);
		} else {
			Keyboard.removeListener('keyboardWillShow', this.keyboardWillShow);
		}
		if (!_.isEmpty(this.debounceErrorToast)) this.debounceErrorToast.cancel();
	}

	keyboardDidShow = () => {
		if (this.scrollView) this.scrollView.scrollToEnd({ animated: true });
	}

	keyboardWillShow = () => {
		if (this.scrollView) this.scrollView.scrollToEnd({ animated: true });
	}

	render() {
		return (
			<View style={styles.container} behavior="position" keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : -300} enabled>
				<View
					style={styles.inputContainer}
				>
					<Text color="black" style={styles.inputLabel}>{i18n.t('users.newPassword')}</Text>
					<TextInput
						name="newPassword"
						testID="tiNewPassword"
						placeholder=""
						autoCapitalize="none"
						autoCorrect={false}
						secureTextEntry
						hideError
					/>
					<Text color="black" style={styles.inputLabel}>{i18n.t('users.confirmNewPassword')}</Text>
					<TextInput
						name="confirmNewPassword"
						testID="tiConfirmNewPassword"
						placeholder=""
						autoCapitalize="none"
						autoCorrect={false}
						secureTextEntry
					/>
				</View>
				<OfflineNotificationBar stack />
				<View style={[styles.bottomContainer]}>
					<ButtonGroup style={{ marginTop: -30 }} position="bottom">
						<ButtonEx
							testID="ChangePasswordButton"
							style={styles.confirmButton}
							block
							disabled={!this.props.isConnected || !this.props.valid}
							onPress={this.props.handleSubmit}
						>
							<Button.Text>{i18n.t('common.saveChanges')}</Button.Text>
						</ButtonEx>
					</ButtonGroup>
				</View>
			</View>
		);
	}
}

const mapStateToProps = (state) => ({
	isConnected: state.network.isConnected,
	languageCode: _.get(state, 'settings.languageCode'),
});

const validate = (values) => {
	let errors = {};
	if (values.newPassword && values.confirmNewPassword) {
		errors = validator({
			newPassword: values.newPassword,
			confirmNewPassword: values.confirmNewPassword,
		}, {
			confirmNewPassword: {
				length: { minimum: 6, message: i18n.t('users.password-invalid') },
				// equality: {
				// 	attribute: 'newPassword',
				// 	message: 'The password and confirmation do not matched',
				// },
			},
		});
	} else {
		errors.newPassword = true;
	}
	return errors;
};

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		if (_.isEqual(values.newPassword, values.confirmNewPassword)) {
			dispatch({
				type: SUBMIT_CHANGE_USER_SETTINGS,
				payload: {
					data: { password: values.confirmNewPassword },
					resolve,
					reject,
				},
			});
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: i18n.t('users.thePasswordDoNotMatch') } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	analytics.logAction('change_password');
	ToasterService.toast({ text: i18n.t('users.passwordUpdated') });
	props.navigation.goBack();
};

const onSubmitFail = (error) => {
	if (!_.isEmpty(error)) {
		let errorString = error.error;
		if (_.isEqual(errorString, 'Your new password cannot be the same as your old password')) {
			errorString = i18n.t('users.errorInvalidSamePassword');
		}
		ToasterService.toast({
			theme: 'error',
			text: errorString,
		});
	}
};

const FormContainer = reduxForm({
	form: 'ChangePassword',
	validate,
	onSubmit,
	onSubmitSuccess,
	onSubmitFail,
})(ChangePassword);

export default connect(mapStateToProps)(FormContainer);
