import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard } from 'react-native';
import { StackActions, NavigationActions } from 'react-navigation';
import DefaultPreference from 'react-native-default-preference';
import PropTypes from 'prop-types';
import { reduxForm, change as changeField } from 'redux-form';
import { connect } from 'react-redux';

import i18n from '~/locale/i18n';
import { validator, emailFormat, nameFormat, isValidEmail } from '~/lib/validate';
import { createConstrains } from '~/lib/validate/preset';
import { Text, color } from 'nixplay-ui-kit';
import { TextInput } from '~comp/reduxForm';
import { Button } from '~comp';
import { FIRST_TIME_INSTALL } from '~/lib/appConstants';
import { SHOW_TOAST_ERROR, UPDATE_REGISTRATION_INFO, CHANGE_APP_ROOT, UPDATE_IS_VERIFIED } from '~/store/actionTypes';

import { color as basicColor } from '~/styles/variables'
import { CustomPicker } from '~comp/AccountSettings/customPicker';

import { styles } from './styles';

let currentState = {};

export class SetLifeStatus 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,
		valid: PropTypes.bool.isRequired,
		submitting: PropTypes.bool.isRequired,
	}

	constructor(props) {
		super(props);

		this.state = {
			index: 0,
			province: '',
			municipality: '',
			barangay: '',
			program: '',
			bottomOpacity: 1
		};

		DefaultPreference.set(FIRST_TIME_INSTALL, '')
		this.goToWebView = this.goToWebView.bind(this);
		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 });
	};

	goToWebView(url) {
		this.props.navigation.push('WebView', { webViewUrl: url });
	}

	onPageSelected = (index) => {
		this.setState({ index });
	}

	setHeaderActions = () => {
		this.props.navigation.setParams({
			onPressSkip: this.onPressSkip,
		});
	}

	setPreference = () => (
		DefaultPreference.set(FIRST_TIME_INSTALL, `${(new Date()).getMilliseconds()}`)
	)

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

	goToSignUp = () => {
		this.setPreference()
			.then(() => {
				this.props.navigation.push('SignUpUserInfo');
			});
	}

	onUpdateHousehold = (household) => {
		this.setState({ household });
		currentState = {...currentState, household };
	}

	householdSelect = () => {
		this.props.navigation.push('HouseholdSelection', { selected: this.state.household, onUpdateHousehold: this.onUpdateHousehold });
	}

	onUpdateDamage = (damage) => {
		this.setState({ damage });
		currentState = {...currentState, damage };
	}

	extendDamageSelect = () => {
		this.props.navigation.push('ExtendDamageSelection', { selected: this.state.damage, onUpdateDamage: this.onUpdateDamage });
	}

	onUpdateProgram = (program) => {
		this.setState({ program });
		currentState = {...currentState, program };
	}

	applyProgramSelect = () => {
		this.props.navigation.push('ApplyProgramSelection', { selected: this.state.program, onUpdateProgram: this.onUpdateProgram });
	}

	render() {
		const { household, damage, program } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.inputContainer}>
					<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 30 }}>Set Life Status</Text>
					<Text style={styles.inputElement} textStyle="subhead">Household Classification</Text>
					<CustomPicker
						action={this.householdSelect}
						itemSelected={(!_.isEmpty(household) ? household : '')}
						name="HouseholdClassification"
						placeholder="Select Household Classification"
					/>
				</View>
				<View style={[styles.inputContainer, { marginTop: 30 }]}>
					<Text style={styles.inputElement} textStyle="subhead">Extend Damage</Text>
					<CustomPicker
						action={this.extendDamageSelect}
						itemSelected={(!_.isEmpty(damage) ? damage : '')}
						name="ExtendDamage"
						placeholder="Select Extend Damage"
					/>
				</View>
				<View style={[styles.inputContainer, { marginTop: 30 }]}>
					<Text style={styles.inputElement} textStyle="subhead">I want to apply program to:</Text>
					<CustomPicker
						action={this.applyProgramSelect}
						itemSelected={(!_.isEmpty(program) ? program : '')}
						name="ApplyProgram"
						placeholder="Select Government Benefit Program"
					/>
				</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="Done"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={(_.isEmpty(household) || _.isEmpty(damage) || _.isEmpty(program))}
							text={i18n.t('common.wereAlmostDone')} />
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const onSubmit = (values, dispatch, ownProps) => (
	new Promise((resolve, reject) => {
		const { household, damage, program } = currentState;
		if (!_.isEmpty(household) && !_.isEmpty(damage) && !_.isEmpty(program)) {
			dispatch({ type: UPDATE_REGISTRATION_INFO, payload: { household, damage, program } });
			resolve('Validated');
		} else {
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	dispatch({
		type: CHANGE_APP_ROOT,
		payload: { root: 'main' },
	});
};

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

export default connect(null, null)(FormContainer);
