import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard, Platform, Alert } from 'react-native';
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 } 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, REQUEST_VERIFY_REFID } from '~/store/actionTypes';
import { styles } from './styles';

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

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		registration: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);

		this.state = {
			bottomOpacity: 1,
			refId: '',
		};

		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 Referrence ID From SMS</Text>
					<Text
						style={styles.inputElement}
						textStyle="subhead"
					>
						Enter Referrence ID
					</Text>
					<TextInput
						name="referrenceID"
						testID="tiReferrenceID"
						placeholder="ex. REF1234567890"
						autoCapitalize="none"
						autoCorrect={false}
						returnKeyType="done"
						maxLength={32}
						keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
						blurOnSubmit
						style={{ color: basicColor.wrikeBg }}
						selectionColor={basicColor.wrikeGreen2}
						onChange={text => {
							this.setState({ refId: text });
							currentState = { ...currentState, refId: text };
						}}
						onSubmitEditing={this.debouncerHandleSubmit}
						defaultText={this.state.refId}

					/>
				</View>
				<View style={styles.checkboxContainer}>
					<View style={styles.checkboxLabel}>
						<Text style={{ color: colorTxt, paddingHorizontal: 18 }} textStyle="subhead">{currentState.data}</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="Get Data"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={hasError}
							text="Get Data"
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		// REQUEST_VERIFY_REFID
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					// console.log('username: ', username, password);
					dispatch({
						type: REQUEST_VERIFY_REFID,
						payload: {
							refId: currentState.refId,
							resolve,
							reject,
						},
					});
				} else {
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		if (!_.isEmpty(currentState.refId)) {
			if (currentState.refId.length === 10) {
				callAPI();
			} else {
				dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'RefID is not valid.' } });
			}
		} else {
			dispatch({ type: SHOW_TOAST, payload: { text: 'Some fields are required.' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch) => {
	// console.log('onSubmitSuccess: ', result);
	if (!_.isEmpty(result)) {
		// result.status
		let dataResponse = `message: ${result.message}, status: ${result.status}`;
		if (parseInt(result.status, 0) === 200) {
			const {
				barangay,
				dob,
				fullName,
				municipality,
				province,
				readableDate,
				regType,
				scanByMemberRefId,
				scanByName,
				scanByUsername,
				sex,
				taggedAssistance,
				username,
			} = result.data;
			dataResponse = `Name: ${fullName}\nDate of Birth: ${dob}\nSex: ${sex}\nUsername: ${username}\nRegType: ${regType}\nTagged Assistance: ${taggedAssistance}\nScan By: ${scanByName}, ${scanByUsername}, ${scanByMemberRefId}\nLocation: ${barangay}, ${municipality}, ${province}\nDATE: ${(new Date(currentState.refId * 1000))}`;
		}
		Alert.alert(
			'MAAGApp - REFID Validation',
			`DATA: ${dataResponse}`,
			[
				{
					text: i18n.t('common.ok'),
					onPress: () => {},
				},
			],
			{ cancelable: false },
		);
	} else {
		// failed to request, bad gateway
		dispatch({ type: SHOW_TOAST, payload: { text: 'Service Request is unavailable. Please try again.' } });
	}
};


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

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

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

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