import '../../../shim.js';
import crypto from 'crypto';
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 { 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 { TextInput } from '~comp/reduxForm';
import { Button } from '~comp';

import { color as basicColor } from '~/styles/variables';
import { CustomPicker } from '~comp/AccountSettings/customPicker';
import { SHOW_TOAST, SHOW_TOAST_ERROR, CHANGE_APP_ROOT, REGISTER_BENEFICIARY } from '~/store/actionTypes';

import { styles } from './styles';

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

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

	static propTypes = {
		navigation: 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', '2');
		const password = props.navigation.getParam('password', 'null');
		const isVerified = props.navigation.getParam('isVerified', false);
		currentState = {
			...currentState, emailAddress, mobileNumber, regType, code, isVerified, password,
		};
		this.state = {
			province: '',
			municipality: '',
			barangay: '',
			bottomOpacity: 1,
		};

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

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

	onUpdateProvice = (province) => {
		this.setState({ province, municipality: '', barangay: '' });
		currentState = {
			...currentState, province, municipality: '', barangay: '',
		};
	}

	provinceSelect = () => {
		this.props.navigation.push('ProvinceSelection', { selected: this.state.province, onUpdateProvice: this.onUpdateProvice });
	}

	onUpdateMunicipality = (municipality) => {
		this.setState({ municipality, barangay: '' });
		currentState = { ...currentState, municipality, barangay: '' };
	}

	municipalitySelect = () => {
		this.props.navigation.push(
			'MunicipalitySelection',
			{
				selected: this.state.municipality,
				provCode: this.state.province.provCode,
				onUpdateMunicipality: this.onUpdateMunicipality,
			},
		);
	}

	onUpdateBarangay = (barangay) => {
		this.setState({ barangay });
		currentState = { ...currentState, barangay };
	}


	barangaySelect = () => {
		this.props.navigation.push(
			'BarangaySelection',
			{
				selected: this.state.barangay,
				citymunCode: this.state.municipality.citymunCode,
				onUpdateBarangay: this.onUpdateBarangay,
			},
		);
	}

	render() {
		const { province, municipality, barangay, fullName } = this.state;
		const hasError = (!_.isEmpty(currentState.gotError));
		return (
			<View style={styles.container}>
				<View style={styles.inputContainer}>
					<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 30 }}>Set Basic Information</Text>
					<Text
						style={styles.inputElement}
						textStyle="subhead"
					>
						Enter Full Name
					</Text>
					<TextInput
						name="fullName"
						testID="tiFullName"
						placeholder="First Middle Surname"
						autoCapitalize="none"
						autoCorrect={false}
						returnKeyType="next"
						keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
						blurOnSubmit
						onSubmitEditing={this.debouncerHandleSubmit}
						style={{ color: basicColor.wrikeBg }}
						selectionColor={basicColor.wrikeGreen2}
						defaultText={fullName}
						onChange={text => this.setState({
							fullName: text,
						})}
					/>
				</View>
				<View style={[styles.inputContainer, { marginTop: -20 }]}>
					<Text style={styles.inputElement} textStyle="subhead">Province</Text>
					<CustomPicker
						action={this.provinceSelect}
						itemSelected={(!_.isEmpty(province) ? province.provDesc : '')}
						name="Province"
						placeholder="Select Province"
					/>
				</View>
				{ (!_.isEmpty(province)) &&
					<View style={[styles.inputContainer, { marginTop: 30 }]}>
						<Text style={styles.inputElement} textStyle="subhead">City / Municipality</Text>
						<CustomPicker
							action={this.municipalitySelect}
							itemSelected={(!_.isEmpty(municipality) ? municipality.citymunDesc : '')}
							name="Municipality"
							placeholder="Select City / Municipality"
						/>
					</View>
				}
				{ (!_.isEmpty(municipality)) &&
					<View style={[styles.inputContainer, { marginTop: 30 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Barangay</Text>
						<CustomPicker
							action={this.barangaySelect}
							itemSelected={(!_.isEmpty(barangay) ? barangay.brgyDesc : '')}
							name="Barangay"
							placeholder="Select Barangay"
						/>
					</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"> </Text>
					</View>
					<View style={styles.buttonContainer}>
						<Button
							testID="Next"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={(hasError || _.isEmpty(province) || _.isEmpty(municipality) || _.isEmpty(barangay))}
							text={i18n.t('common.next')}
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

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

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const { fullName } = values;
		let emailAddress = _.get(currentState, 'emailAddress', 'null');
		let mobileNumber = _.get(currentState, 'mobileNumber', 'null');
		const password = _.get(currentState, 'password', 'null');
		const username = (!_.isEmpty(mobileNumber) && mobileNumber.length > 10) ? mobileNumber : emailAddress;
		emailAddress = (!_.isEmpty(emailAddress)) ? emailAddress : 'null';
		mobileNumber = (!_.isEmpty(mobileNumber)) ? mobileNumber : 'null';
		const memberRefId = crypto.randomBytes(20).toString('hex');
		const { barangay, municipality, province } = currentState;
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					dispatch({
						type: REGISTER_BENEFICIARY,
						payload: {
							username,
							fullName,
							firstName: 'null',
							lastName: 'null',
							middleName: 'null',
							age: 'null',
							dob: 'null',
							program: 'null',
							programID: 'null',
							remarks: 'null',
							nationalId: 'null',
							idNumber: 'null',
							regCode: 'null',
							region: 'null',
							provCode: province.provCode,
							province: province.provDesc,
							citymunCode: municipality.citymunCode,
							municipality: municipality.citymunDesc,
							brgyCode: barangay.brgyCode,
							barangay: barangay.brgyDesc,
							suffix: 'null',
							sex: 'null',
							ethnicity: 'null',
							occupation: 'null',
							sector: 'null',
							monthlyIncome: 'null',
							education: 'null',
							houseOwnership: 'null',
							healthCondition: 'null',
							mobileNumber,
							emailAddress,
							password,
							regType: '2',
							memberRefId,
							resolve,
							reject,
						},
					});
				} else {
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		if (!_.isEmpty(fullName) && !_.isEmpty(province) && !_.isEmpty(municipality) && !_.isEmpty(barangay)) {
			// dispatch({
			// 	type: UPDATE_REGISTRATION_INFO,
			// 	payload: {
			// 		barangay, municipality, province, fullName,
			// 	},
			// });
			// console.log('onSubmit>currectState: ', barangay.brgyDesc, municipality.citymunDesc, province.provDesc, fullName);
			// resolve('Validated');
			callAPI();
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Some fields are required' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch) => {
	// console.log('onSubmitSuccess: ', props);
	// props.navigation.push('SetLifeStatus');
	dispatch({
		type: CHANGE_APP_ROOT,
		payload: { root: 'main' },
	});
};

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

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

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

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