import _ from 'lodash';
import React, { Component } from 'react';
import {
	SafeAreaView,
	View,
	Keyboard,
	ScrollView,
	TouchableOpacity,
	Image,
	PixelRatio,
	Platform,
} from 'react-native';
import ImageResizer from 'react-native-image-resizer';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { Text, Avatar, NixplayIcon as Icon, color } from 'nixplay-ui-kit';

import i18n from '~/locale/i18n';
import { validator } from '~/lib/validate';
import { createConstrains } from '~/lib/validate/preset';
import { TextInput } from '~comp/reduxForm';
import { Button } from '~comp';
import { PickerOptions } from '~/components/Photos/pickerOptions';


import { color as basicColor } from '~/styles/variables';
import { CustomPicker } from '~comp/AccountSettings/customPicker';
import { SHOW_TOAST, SAVE_BENE_RECORD, GET_ASSETS } from '~/store/actionTypes';
import { styles } from './styles';
import { set } from 'react-native-reanimated';

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

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		// isLoggedIn: PropTypes.bool.isRequired,
		handleSubmit: PropTypes.func.isRequired,
		dirty: PropTypes.bool.isRequired,
		// submitting: PropTypes.bool.isRequired,
		launchImagePicker: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);
		currentState = {};
		const fullName = this.props.navigation.getParam('fullName', '');
		const mobileNumber = this.props.navigation.getParam('mobileNumber', '');
		currentState = {
			...currentState, fullName, mobileNumber,
		};
		// console.log('current: ', currentState);
		this.state = {
			SACFormID: '',
			region: '',
			province: '',
			municipality: '',
			barangay: '',
			cRegion: '',
			cProvince: '',
			cMunicipality: '',
			cBarangay: '',
			bottomOpacity: 1,
			sector: '',
			sex: '',
			ethnicity: '',
			dob: '',
			occupation: '',
			monthlyIncome: '',
			education: '',
			houseOwnership: '',
			healthCondition: '',
			program: '',
			programID: '',
			nationalId: '',
			idNumber: '',
			// reliefAssistance: '',
			remarks: '',
			lastName: '',
			firstName: '',
			middleName: '',
			suffix: '',
			beneficiaryMobile: '',
			avatarPhoto: null,
			dobColor: basicColor.wrikeBg,
		};

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

	// Place of Birth
	onUpdateRegion = (region) => {
		console.log('region');
		this.setState({ region, province: '', municipality: '', barangay: '' });
		currentState = {...currentState, region, province: '', municipality: '', barangay: '' };
	}
	regionSelect = () => {
		console.log('regionSelect')
		this.props.navigation.push('RegionSelection',{
			selected: this.state.region,
			onUpdateRegion: this.onUpdateRegion,
			origin: 1
		});
	}

	onUpdateProvice = (province) => {
		this.setState({ province, municipality: '', barangay: '' });
		currentState = {...currentState, province, municipality: '', barangay: '' };
	}
	provinceSelect = () => {
		this.props.navigation.push('ProvinceSelection',{
			selected: this.state.province,
			region: this.state.region.regCode,
			onUpdateProvice: this.onUpdateProvice,
			origin: 1
		});
	}

	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,
				origin: 1,
			},
		);
	}

	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,
				origin: 1,
			},
		);
	}
	// Current Address
	onUpdateCRegion = (region) => {
		this.setState({ cRegion: region, cProvince: '', cMunicipality: '', cBarangay: '' });
		currentState = { ...currentState, cRegion: region, cProvince: '', cMunicipality: '', cBarangay: '' };
	}
	cRegionSelect = () => {
		this.props.navigation.push(
			'RegionSelection',
			{
				selected: this.state.cRegion,
				onUpdateRegion: this.onUpdateCRegion,
				origin: 1,
			},
		);
	}
	onUpdateCProvice = (province) => {
		this.setState({ cProvince: province, cMunicipality: '', cBarangay: '' });
		currentState = {...currentState, cProvince: province, cMunicipality: '', cBarangay: '' };
	}
	cProvinceSelect = () => {
		this.props.navigation.push(
			'ProvinceSelection',
			{
				selected: this.state.cProvince,
				region: this.state.cRegion.regCode,
				onUpdateProvice: this.onUpdateCProvice,
				origin: 1,
			},
		);
	}
	onUpdateCMunicipality = (municipality) => {
		this.setState({ cMunicipality: municipality, cBarangay: '' });
		currentState = {...currentState, cMunicipality: municipality, cBarangay: '' };
	}
	cMunicipalitySelect = () => {
		this.props.navigation.push(
			'MunicipalitySelection',
			{
				selected: this.state.cMunicipality,
				provCode: this.state.cProvince.provCode,
				onUpdateMunicipality: this.onUpdateCMunicipality,
				origin: 1,
			},
		);
	}
	onUpdateCBarangay = (barangay) => {
		this.setState({ cBarangay: barangay });
		currentState = {...currentState, cBarangay: barangay };
	}
	cBarangaySelect = () => {
		this.props.navigation.push(
			'BarangaySelection',
			{
				selected: this.state.cBarangay,
				citymunCode: this.state.cMunicipality.citymunCode,
				onUpdateBarangay: this.onUpdateCBarangay,
				origin: 1,
			},
		);
	}

	onUpdateEthnic = (ethnicity) => {
		this.setState({ ethnicity });
		currentState = { ...currentState, ethnicity };
	}
	ethnicSelect = () => {
		this.props.navigation.push(
			'EthnicSelection',
			{
				selected: this.state.ethnicity,
				onUpdate: this.onUpdateEthnic,
				origin: 1,
			},
		);
	}
	// onUpdateOccupation = (occupation) => {
	// 	this.setState({ occupation });
	// 	currentState = {...currentState, occupation };
	// }
	// occupationSelect = () => {
	// 	this.props.navigation.push(
	// 		'OccupationSelection',
	// 		{
	// 			selected: this.state.occupation,
	// 			onUpdate: this.onUpdateOccupation,
	// 			origin: 1,
	// 		},
	// 	);
	// }
	onUpdateEducation = (education) => {
		this.setState({ education });
		currentState = { ...currentState, education };
	}
	educationSelect = () => {
		this.props.navigation.push(
			'EducationSelection',
			{
				selected: this.state.education,
				onUpdate: this.onUpdateEducation,
				origin: 1,
			},
		);
	}
	onUpdateSector = (sector) => {
		this.setState({ sector });
		currentState = {...currentState, sector };
	}
	sectorSelect = () => {
		this.props.navigation.push(
			'SectorSelection',
			{
				selected: this.state.sector,
				onUpdate: this.onUpdateSector,
				origin: 1,
			},
		);
	}
	onUpdateMonthIncome = (monthlyIncome) => {
		this.setState({ monthlyIncome });
		currentState = { ...currentState, monthlyIncome };
	}
	monthIncomeSelect = () => {
		this.props.navigation.push(
			'MonthIncomeSelection',
			{
				selected: this.state.monthlyIncome,
				onUpdate: this.onUpdateMonthIncome,
				origin: 1,
			},
		);
	}
	onUpdateHouseOwnership = (houseOwnership) => {
		this.setState({ houseOwnership });
		currentState = { ...currentState, houseOwnership };
	}
	houseOwnershipSelect = () => {
		this.props.navigation.push(
			'HouseholdSelection',
			{
				selected: this.state.houseOwnership,
				onUpdateHousehold: this.onUpdateHouseOwnership,
				origin: 1,
			},
		);
	}
	onUpdateHealth = (healthCondition) => {
		this.setState({ healthCondition });
		currentState = { ...currentState, healthCondition };
	}
	healthSelect = () => {
		this.props.navigation.push(
			'HealthSelection',
			{
				selected: this.state.healthCondition,
				onUpdate: this.onUpdateHealth,
				origin: 1,
			},
		);
	}
	onUpdateNatID = (nationalId) => {
		this.setState({ nationalId });
		currentState = { ...currentState, nationalId };
	}
	natIDSelect = () => {
		this.props.navigation.push(
			'NatIDSelection',
			{
				selected: this.state.nationalId,
				onUpdate: this.onUpdateNatID,
				origin: 1,
			},
		);
	}

	// onUpdateReliefAssitance = (reliefAssistance) => {
	// 	this.setState({ reliefAssistance });
	// 	currentState = { ...currentState, reliefAssistance };
	// }
	// reliefSelect = () => {
	// 	this.props.navigation.push(
	// 		'ReliefSelection',
	// 		{
	// 			selected: this.state.reliefAssistance,
	// 			onUpdate: this.onUpdateReliefAssitance,
	// 			origin: 1,
	// 		},
	// 	);
	// }

	onUpdateSuffix = (suffix) => {
		this.setState({ suffix });
		currentState = { ...currentState, suffix };
	}
	suffixSelect = () => {
		this.props.navigation.push(
			'SuffixSelection',
			{
				selected: this.state.suffix,
				onUpdate: this.onUpdateSuffix,
				origin: 1,
			},
		);
	}

	onUpdateGender = (sex) => {
		this.setState({ sex });
		currentState = { ...currentState, sex };
	}
	genderSelect = () => {
		this.props.navigation.push(
			'GenderSelection',
			{
				selected: this.state.sex,
				onUpdate: this.onUpdateGender,
				origin: 1,
			},
		);
	}
	onUpdateProgram = (program) => {
		this.setState({ program });
		currentState = { ...currentState, program };
	}
	programSelect = () => {
		this.props.navigation.push(
			'ProgramSelection',
			{
				selected: this.state.program,
				onUpdate: this.onUpdateProgram,
				origin: 1,
			},
		);
	}

	processSourceImage = (rawImage) => {
		this.setState({ }, async () => {
			try {
				let sourceUri = rawImage;
				Image.getSize(sourceUri, async (w, h) => {
					const safeSize = PixelRatio.roundToNearestPixel(1000); // approximate preferred max dimension size
					let width = w;
					let height = h;

					if (width > safeSize && width > height) {
						const percentageDiff = (safeSize / width);
						width = safeSize;
						height = PixelRatio.roundToNearestPixel(height * percentageDiff);
					} else if (height > safeSize && height > width) {
						const percentageDiff = (safeSize / height);
						height = safeSize;
						width = PixelRatio.roundToNearestPixel(width * percentageDiff);
					}
					const resizedImage = await ImageResizer.createResizedImage(sourceUri, width, height, 'JPEG', 100, 0, null);
					sourceUri = resizedImage.uri;
					this.setState({ avatarPhoto: sourceUri });
					currentState = { ...currentState, avatarPhoto: sourceUri };
				}, (e) => {
					console.log('error2: ', e);
				});
			} catch (e) {
				console.log('error1: ', e);
			}
		});
	};

	launchImagePicker = () => {
		this.props.launchImagePicker({
			options: {
				...PickerOptions([]),
				maximumImageCount: 1,
				imageSelectionLimit: i18n.t('contents.imageSelectionLimit', { count: 1 }),
				mediaType: 'image',
				allowsMultipleSelection: '0',
			},
			resolve: (imagesPicked) => {
				if (imagesPicked && imagesPicked[0] && imagesPicked[0].uri) {
					console.log('IMAGE: ', imagesPicked[0].uri);
					this.processSourceImage(imagesPicked[0].uri);
				}
			},
		});
	}

	onChangeTextDob = (text) => {
		const isDeleting = (text.length < this.state.dob.length);
		let tempText = text.replace(/-/g, '');
		let dobColor = basicColor.wrikeBg;
		// eslint-disable-next-line no-restricted-globals
		if (!isNaN(tempText)) {
			if (tempText.length >= 2) {
				if ((parseInt(tempText.substr(0, 2), 0) >= 13)
					|| (parseInt(tempText.substr(2, 2), 0) >= 32)
					|| (parseInt(tempText.substr(4, 4), 0) > (new Date()).getFullYear())) {
					dobColor = basicColor.red;
				}
			}
		} else {
			dobColor = basicColor.red;
		}
		if (!isDeleting && tempText.length === 2) {
			tempText = [tempText.slice(0, 2), '-', tempText.slice(2)].join('');
		} else if (!isDeleting && !_.isEqual(dobColor, basicColor.red) && tempText.length === 4) {
			tempText = [tempText.slice(0, 2), '-', tempText.slice(2)].join('').concat('-');
		} else {
			tempText = text;
		}
		currentState = { ...currentState, dobError: (_.isEqual(dobColor, basicColor.red)) };
		this.setState({ dob: tempText, dobColor });
	}

	render() {
		// console.log('render: ', this.state.avatarPhoto);

		const {
			region, province, municipality, barangay,
			cRegion, cProvince, cMunicipality, cBarangay,
			lastName, firstName, middleName, suffix,
			sex, ethnicity, dob,
			occupation, sector, monthlyIncome,
			education, houseOwnership, healthCondition,
			program, programID, nationalId, idNumber,
			remarks, dobColor,
			beneficiaryMobile, emailAddress, SACFormID,
		} = this.state;
		// const hasError = (!_.isEmpty(currentState.gotError));
		const dobErrorColor = (currentState.dobError) ? color.red : color.borderMistBlue;
		const lnameColor = (currentState.lastNameError) ? color.red : color.borderMistBlue;
		const fnameColor = (currentState.firstNameError) ? color.red : color.borderMistBlue;
		const mnameColor = (currentState.middleNameError) ? color.red : color.borderMistBlue;
		const beMobColor = (currentState.beneficiaryMobileError) ? color.red : color.borderMistBlue;
		const occupColor = (currentState.occupationError) ? color.red : color.borderMistBlue;
		return (
			<View style={styles.container}>
				<ScrollView
					style={{
						flex: 1,
					}}
					contentContainerStyle={styles.contentContainer}
					showsVerticalScrollIndicator={false}
					showsHorizontalScrollIndicator={false}
				>
					<View style={styles.inputContainer}>
						<Text textStyle="headline" color={basicColor.orange} style={{ textAlign: 'left', marginBottom: 10, paddingLeft: 0 }}>Basic Information</Text>
						<View style={{ backgroundColor: basicColor.orange, height: 0.5, marginHorizontal: 0, opacity: 0.8 }} />
						<Text
							style={[styles.inputElement, { marginTop: 15 }]}
							textStyle="subhead"
						>
							SAC Form ID
						</Text>
						<TextInput
							name="SACFormID"
							testID="tiSACFormID"
							placeholder="SAC Form ID"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={SACFormID}
							onChange={text => this.setState({ SACFormID: text })}
						/>
						<Text
							style={[styles.inputElement, { marginTop: 5 }]}
							textStyle="subhead"
						>
							Last Name
						</Text>
						<TextInput
							name="lastName"
							testID="tiLastName"
							placeholder="Last name"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, borderColor: lnameColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={lastName}
							onChange={text => this.setState({ lastName: text })}
						/>
						<Text
							style={styles.inputElement}
							textStyle="subhead"
						>
							First Name
						</Text>
						<TextInput
							name="firstName"
							testID="tiFirstName"
							placeholder="First name"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, borderColor: fnameColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={firstName}
							onChange={text => this.setState({ firstName: text })}
						/>
						<Text
							style={styles.inputElement}
							textStyle="subhead"
						>
							Middle Name
						</Text>
						<TextInput
							name="middleName"
							testID="tiMiddleName"
							placeholder="Middle name"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, borderColor: mnameColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={middleName}
							onChange={text => this.setState({ middleName: text })}
						/>
						<Text style={styles.inputElement} textStyle="subhead">Suffix</Text>
						<CustomPicker
							action={this.suffixSelect}
							itemSelected={(!_.isEmpty(suffix) ? suffix : '')}
							name="suffix"
							placeholder="Select Suffix"
						/>
						<Text style={[styles.inputElement, { marginTop: 10 }]} textStyle="subhead">Sex</Text>
						<CustomPicker
							action={this.genderSelect}
							itemSelected={(!_.isEmpty(sex) ? sex : '')}
							name="gender"
							placeholder="Select Sex"
							hasError={currentState.sexError}
						/>
						<Text
							style={[styles.inputElement, { marginTop: 5 }]}
							textStyle="subhead"
						>
							Date of Birth
						</Text>
						<TextInput
							name="dob"
							testID="tiDob"
							placeholder="MM-DD-YYYY"
							autoCapitalize="none"
							autoCorrect={false}
							maxLength={10}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: dobColor, borderColor: dobErrorColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={dob}
							onChange={this.onChangeTextDob}
						/>
						<Text
							style={[styles.inputElement, { marginTop: 5 }]}
							textStyle="subhead"
						>
							Mobile Number
						</Text>
						<TextInput
							name="beneficiaryMobile"
							testID="tiBeneficiaryMobile"
							placeholder="+63"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							maxLength={13}
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, borderColor: beMobColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={beneficiaryMobile}
							onFocus={() => { if (_.isEmpty(beneficiaryMobile)) { this.setState({ beneficiaryMobile: '+63' }); } }}
							onChange={text => { this.setState({ beneficiaryMobile: text }); }}
						/>
						<Text
							style={[styles.inputElement, { marginTop: 5 }]}
							textStyle="subhead"
						>
							Email Address
						</Text>
						<TextInput
							name="emailAddress"
							testID="tiEmailAddress"
							placeholder="ex. abc@gmail.com"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={emailAddress}
							onChange={text => this.setState({ emailAddress: text })}
						/>
						<Text
							style={[styles.inputElement, { marginTop: 5 }]}
							textStyle="subhead"
						>
							Educational Attainment
						</Text>
						<CustomPicker
							action={this.educationSelect}
							itemSelected={(!_.isEmpty(education) ? education : '')}
							name="Education"
							placeholder="Select Educational Attainment"
							hasError={currentState.educationError}
						/>
					</View>
					<View style={styles.checkboxContainer}>
						<View style={styles.checkboxLabel}>
							<Text style={{ color: basicColor.gitlabGray4, paddingHorizontal: 18 }} textStyle="subhead"> </Text>
						</View>
					</View>
					{/* <View> Place of Birth </View> */}
					<Text textStyle="headline" color={basicColor.blue} style={{ textAlign: 'left', marginVertical: 10, paddingLeft: 20 }}>Place of Birth</Text>
					<View style={{ backgroundColor: basicColor.blue, height: 0.5, marginHorizontal: 20, opacity: 0.8 }} />
					<View style={[styles.inputContainer, { marginTop: 10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Region</Text>
						<CustomPicker
							action={this.regionSelect}
							itemSelected={(!_.isEmpty(region) ? region.regDesc : '')}
							name="PobProvince"
							placeholder="Select Region"
							hasError={currentState.regionError}
						/>
					</View>
					{ (!_.isEmpty(region)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Province</Text>
							<CustomPicker
								action={this.provinceSelect}
								itemSelected={(!_.isEmpty(province) ? province.provDesc : '')}
								name="PobProvince"
								placeholder="Select Province"
								hasError={currentState.provinceError}
							/>
						</View>
					}
					{ (!_.isEmpty(province)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Municipality</Text>
							<CustomPicker
								action={this.municipalitySelect}
								itemSelected={(!_.isEmpty(municipality) ? municipality.citymunDesc : '')}
								name="PobMunicipality"
								placeholder="Select Municipality"
								hasError={currentState.municipalityError}
							/>
						</View>
					}
					{ (!_.isEmpty(municipality)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Barangay</Text>
							<CustomPicker
								action={this.barangaySelect}
								itemSelected={(!_.isEmpty(barangay) ? barangay.brgyDesc : '')}
								name="PobBarangay"
								placeholder="Select Barangay"
							/>
						</View>
					}
					<View style={styles.checkboxContainer}>
						<View style={styles.checkboxLabel}>
							<Text style={{ color: basicColor.gitlabGray4, paddingHorizontal: 18 }} textStyle="subhead"> </Text>
						</View>
					</View>
					{/* <View> Current Address </View> */}
					<Text textStyle="headline" color={basicColor.wrikeGreen2} style={{ textAlign: 'left', marginVertical: 10, paddingLeft: 20 }}>Current Address</Text>
					<View style={{ backgroundColor: basicColor.wrikeGreen2, height: 0.5, marginHorizontal: 20, opacity: 0.8 }} />
					<View style={[styles.inputContainer, { marginTop: 10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Region</Text>
						<CustomPicker
							action={this.cRegionSelect}
							itemSelected={(!_.isEmpty(cRegion) ? cRegion.regDesc : '')}
							name="Region"
							placeholder="Select Region"
							hasError={currentState.cRegionError}
						/>
					</View>
					{ (!_.isEmpty(cRegion)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Province</Text>
							<CustomPicker
								action={this.cProvinceSelect}
								itemSelected={(!_.isEmpty(cProvince) ? cProvince.provDesc : '')}
								name="Province"
								placeholder="Select Province"
								hasError={currentState.cProvinceError}
							/>
						</View>
					}
					{ (!_.isEmpty(cProvince)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Municipality</Text>
							<CustomPicker
								action={this.cMunicipalitySelect}
								itemSelected={(!_.isEmpty(cMunicipality) ? cMunicipality.citymunDesc : '')}
								name="Municipality"
								placeholder="Select Municipality"
								hasError={currentState.cMunicipalityError}
							/>
						</View>
					}
					{ (!_.isEmpty(cMunicipality)) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Barangay</Text>
							<CustomPicker
								action={this.cBarangaySelect}
								itemSelected={(!_.isEmpty(cBarangay) ? cBarangay.brgyDesc : '')}
								name="Barangay"
								placeholder="Select Barangay"
								hasError={currentState.cBarangayError}
							/>
						</View>
					}
					<View style={styles.checkboxContainer}>
						<View style={styles.checkboxLabel}>
							<Text style={{ color: basicColor.gitlabGray4, paddingHorizontal: 18 }} textStyle="subhead"> </Text>
						</View>
					</View>
					{/* <View> Educational Background </View> */}
					<Text textStyle="headline" color={basicColor.mistBlue05} style={{ textAlign: 'left', marginVertical: 10, paddingLeft: 20 }}>Other details</Text>
					<View style={{ backgroundColor: basicColor.mistBlue05, height: 0.5, marginHorizontal: 20, opacity: 0.8 }} />
					<View style={[styles.inputContainer, { marginTop: 10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Type of Ethnicity</Text>
						<CustomPicker
							action={this.ethnicSelect}
							itemSelected={(!_.isEmpty(ethnicity) ? ethnicity : '')}
							name="Ethnicity"
							placeholder="Select Ethnicity"
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Occupation</Text>
						{/* <CustomPicker
							action={this.occupationSelect}
							itemSelected={(!_.isEmpty(occupation) ? occupation : '')}
							name="Occupation"
							placeholder="Select Occupation"
						/> */}
						<TextInput
							name="occupation"
							testID="tiOccupation"
							placeholder="Set Occupation"
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg, borderColor: occupColor }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={occupation}
							onChange={text => this.setState({ occupation: text })}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Sector</Text>
						<CustomPicker
							action={this.sectorSelect}
							itemSelected={(!_.isEmpty(sector) ? sector : '')}
							name="Sector"
							placeholder="Select Sector"
							hasError={currentState.sectorError}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Monthly Income</Text>
						<CustomPicker
							action={this.monthIncomeSelect}
							itemSelected={(!_.isEmpty(monthlyIncome) ? monthlyIncome : '')}
							name="MonthlyIncome"
							placeholder="Select Monthly Income"
							hasError={currentState.monthlyIncomeError}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">House Ownership</Text>
						<CustomPicker
							action={this.houseOwnershipSelect}
							itemSelected={(!_.isEmpty(houseOwnership) ? houseOwnership : '')}
							name="HouseOwnership"
							placeholder="Select House Ownership"
							hasError={currentState.houseOwnershipError}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Health Condition</Text>
						<CustomPicker
							action={this.healthSelect}
							itemSelected={(!_.isEmpty(healthCondition) ? healthCondition : '')}
							name="healthCondition"
							placeholder="Select Health Condition"
							hasError={currentState.healthConditionError}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Government ID</Text>
						<CustomPicker
							action={this.natIDSelect}
							itemSelected={(!_.isEmpty(nationalId) ? nationalId : '')}
							name="nationalId"
							placeholder="Select Government ID"
						/>
					</View>
					{ (!_.isEqual(nationalId, 'None')) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text
								style={[styles.inputElement]}
								textStyle="subhead"
							>
								Presented ID Number
							</Text>
							<TextInput
								name="idNumber"
								testID="tiIdNumber"
								placeholder="Ex. 12345-678-9"
								autoCapitalize="none"
								autoCorrect={false}
								returnKeyType="next"
								keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
								blurOnSubmit
								onSubmitEditing={this.debouncerHandleSubmit}
								style={{ color: basicColor.wrikeBg, borderColor: basicColor.mistBlue02 }}
								selectionColor={basicColor.wrikeGreen2}
								defaultText={idNumber}
								onChange={text => this.setState({ idNumber: text })}
							/>
						</View>
					}
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Government Benefit Program</Text>
						<CustomPicker
							action={this.programSelect}
							itemSelected={(!_.isEmpty(program) ? program : '')}
							name="program"
							placeholder="Select Government Benefit Program"
							hasError={currentState.programError}
						/>
					</View>
					{ (_.isEqual(program, 'Pantawid')) &&
						<View style={[styles.inputContainer, { marginTop: -10 }]}>
							<Text
								style={[styles.inputElement]}
								textStyle="subhead"
							>
								Government Benefit Program ID
							</Text>
							<TextInput
								name="programID"
								testID="tiProgramID"
								placeholder="Ex. 12345-678-9"
								autoCapitalize="none"
								autoCorrect={false}
								returnKeyType="next"
								keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
								blurOnSubmit
								onSubmitEditing={this.debouncerHandleSubmit}
								style={{ color: basicColor.wrikeBg, borderColor: basicColor.mistBlue02 }}
								selectionColor={basicColor.wrikeGreen2}
								defaultText={programID}
								onChange={text => this.setState({ programID: text })}
							/>
						</View>
					}
					{/* <View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Relief Assitance Received from Government</Text>
						<CustomPicker
							action={this.reliefSelect}
							itemSelected={(!_.isEmpty(reliefAssistance) ? reliefAssistance : '')}
							name="ReliefAssitance"
							placeholder="Select Relief Assistance"
						/>
					</View> */}
					<View style={[styles.inputContainer, { marginTop: -10, marginBottom: 0 }]}>
						<Text
							style={[styles.inputElement]}
							textStyle="subhead"
						>
							Remarks
						</Text>
						<TextInput
							name="remarks"
							testID="tiRemarks"
							placeholder=""
							autoCapitalize="none"
							autoCorrect={false}
							returnKeyType="next"
							keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
							blurOnSubmit
							onSubmitEditing={this.debouncerHandleSubmit}
							style={{ color: basicColor.wrikeBg }}
							selectionColor={basicColor.wrikeGreen2}
							defaultText={remarks}
							onChange={text => this.setState({ remarks: text })}
						/>
					</View>
					<View style={[styles.inputContainer, { marginTop: -10 }]}>
						<Text
							style={[styles.inputElement]}
							textStyle="subhead"
						>
							Add Profile Photo
						</Text>
					</View>
					<View style={styles.profileContent}>
						<Avatar
							firstName={(!_.isEmpty(this.state.firstName) ? this.state.firstName : 'M')}
							lastName={(!_.isEmpty(this.state.lastName) ? this.state.lastName : 'E')}
							size="large"
							source={(!_.isEmpty(this.state.avatarPhoto) ? { uri: this.state.avatarPhoto } : null)}
						/>
						<TouchableOpacity
							style={styles.avatarEditContainer}
							onPress={this.launchImagePicker}
						>
							<Icon
								name="camera"
								color="blue"
								size={16}
							/>
						</TouchableOpacity>
					</View>
					<View style={styles.checkboxContainer}>
						<View style={styles.checkboxLabel}>
							<Text style={{ color: basicColor.gitlabGray4, paddingHorizontal: 18 }} textStyle="subhead" />
						</View>
					</View>
				</ScrollView>
				<SafeAreaView style={[styles.safeArea, { opacity: this.state.bottomOpacity }]}>
					<View style={styles.buttonContainer}>
						<Button
							testID="Saved"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							text="Save Record"
							disabled={!this.props.dirty}
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const onSubmit = (values, dispatch) => (
	new Promise((resolve, reject) => {
		const SACFormID = _.get(values, 'SACFormID', '');
		const firstName = _.get(values, 'firstName', '');
		const lastName = _.get(values, 'lastName', '');
		const middleName = _.get(values, 'middleName', '');
		const dob = _.get(values, 'dob', '');
		const programID = _.get(values, 'programID', '');
		const remarks = _.get(values, 'remarks', '');
		const idNumber = _.get(values, 'idNumber', '');
		const emailAddress = _.get(values, 'emailAddress', '');
		const beneficiaryMobile = _.get(values, 'beneficiaryMobile', '');
		const occupation = _.get(values, 'occupation', '');
		const age = (!_.isEmpty(dob) && dob.length >= 10) ? (new Date()).getFullYear() - (dob.substr(6, 10)) : '0';
		const {
			region, province, municipality, barangay, cRegion, cProvince, cMunicipality, cBarangay,
			suffix, sex, ethnicity, sector, monthlyIncome,
			education, houseOwnership, healthCondition,
			program, nationalId, fullName, mobileNumber,
			dobError,
		} = currentState;
		const avatarPhoto = _.get(currentState, 'avatarPhoto', '');
		const epochtime = Math.floor(new Date().getTime() / 1000.0);
		// console.log('onSubmit>VALUES: ', firstName, lastName, middleName, age, dob);
		// console.log('onSubmit>STATE: ', sex, ethnicity, occupation, monthlyIncome, education, houseOwnership, healthCondition, program, reliefAssistance);
		// beneficiaryMobile
		if (_.isEmpty(beneficiaryMobile)) {
			currentState = { ...currentState, beneficiaryMobileError: true };
		} else {
			currentState = { ...currentState, beneficiaryMobileError: false };
		}
		// lastName
		if (_.isEmpty(lastName)) {
			currentState = { ...currentState, lastNameError: true };
		} else {
			currentState = { ...currentState, lastNameError: false };
		}
		// firstName
		if (_.isEmpty(lastName)) {
			currentState = { ...currentState, firstNameError: true };
		} else {
			currentState = { ...currentState, firstNameError: false };
		}
		// middleName
		if (_.isEmpty(middleName)) {
			currentState = { ...currentState, middleNameError: true };
		} else {
			currentState = { ...currentState, middleNameError: false };
		}
		// region
		if (_.isEmpty(region)) {
			currentState = { ...currentState, regionError: true };
		} else {
			currentState = { ...currentState, regionError: false };
		}
		// province
		if (_.isEmpty(province)) {
			currentState = { ...currentState, provinceError: true };
		} else {
			currentState = { ...currentState, provinceError: false };
		}
		// municipality
		if (_.isEmpty(municipality)) {
			currentState = { ...currentState, municipalityError: true };
		} else {
			currentState = { ...currentState, municipalityError: false };
		}
		// cRegion
		if (_.isEmpty(cRegion)) {
			currentState = { ...currentState, cRegionError: true };
		} else {
			currentState = { ...currentState, cRegionError: false };
		}
		// cProvince
		if (_.isEmpty(cProvince)) {
			currentState = { ...currentState, cProvinceError: true };
		} else {
			currentState = { ...currentState, cProvinceError: false };
		}
		// cMunicipality
		if (_.isEmpty(cMunicipality)) {
			currentState = { ...currentState, cMunicipalityError: true };
		} else {
			currentState = { ...currentState, cMunicipalityError: false };
		}
		// cBarangay
		if (_.isEmpty(cBarangay)) {
			currentState = { ...currentState, cBarangayError: true };
		} else {
			currentState = { ...currentState, cBarangayError: false };
		}
		// sex
		if (_.isEmpty(sex)) {
			currentState = { ...currentState, sexError: true };
		} else {
			currentState = { ...currentState, sexError: false };
		}
		// monthlyIncome
		if (_.isEmpty(monthlyIncome)) {
			currentState = { ...currentState, monthlyIncomeError: true };
		} else {
			currentState = { ...currentState, monthlyIncomeError: false };
		}
		// education
		if (_.isEmpty(education)) {
			currentState = { ...currentState, educationError: true };
		} else {
			currentState = { ...currentState, educationError: false };
		}
		// houseOwnership
		if (_.isEmpty(houseOwnership)) {
			currentState = { ...currentState, houseOwnershipError: true };
		} else {
			currentState = { ...currentState, houseOwnershipError: false };
		}
		// healthCondition
		if (_.isEmpty(healthCondition)) {
			currentState = { ...currentState, healthConditionError: true };
		} else {
			currentState = { ...currentState, healthConditionError: false };
		}
		// program
		if (_.isEmpty(program)) {
			currentState = { ...currentState, programError: true };
		} else {
			currentState = { ...currentState, programError: false };
		}
		// occupation
		if (_.isEmpty(occupation)) {
			currentState = { ...currentState, occupationError: true };
		} else {
			currentState = { ...currentState, occupationError: false };
		}
		// sector
		if (_.isEmpty(sector)) {
			currentState = { ...currentState, sectorError: true };
		} else {
			currentState = { ...currentState, sectorError: false };
		}
		// error
		if (_.isEmpty(dob)) {
			currentState = { ...currentState, dobError: true };
		} else {
			currentState = { ...currentState, dobError: false };
		}

		const username = (!_.isEmpty(beneficiaryMobile)) ? beneficiaryMobile : emailAddress;

		if (!_.isEmpty(beneficiaryMobile) && !_.isEmpty(lastName) && !_.isEmpty(firstName)
			&& !_.isEmpty(dob) && !_.isEmpty(region) && !_.isEmpty(province) && !_.isEmpty(municipality)
			&& !_.isEmpty(cRegion) && !_.isEmpty(cProvince) && !_.isEmpty(cMunicipality) && !_.isEmpty(cBarangay)
			&& !_.isEmpty(sex) && !_.isEmpty(monthlyIncome) && !_.isEmpty(education) && !_.isEmpty(sector)
			&& !_.isEmpty(houseOwnership) && !_.isEmpty(healthCondition) && !_.isEmpty(program)
			&& !dobError && !_.isEmpty(occupation)) {
			// mixpanel entry
			// try {
			// 	Mixpanel.trackWithProperties('add_beneficiary', {
			// 		firstName,
			// 		lastName,
			// 		middleName,
			// 		age,
			// 		dob,
			// 		programID,
			// 		remarks,
			// 		idNumber,
			// 		region,
			// 		province,
			// 		municipality,
			// 		barangay,
			// 		cRegion,
			// 		cProvince,
			// 		cMunicipality,
			// 		cBarangay,
			// 		suffix,
			// 		sex,
			// 		ethnicity,
			// 		occupation,
			// 		sector,
			// 		monthlyIncome,
			// 		education,
			// 		houseOwnership,
			// 		healthCondition,
			// 		program,
			// 		nationalId,
			// 		reliefAssistance,
			// 		emailAddress,
			// 		beneficiaryMobile,
			// 		volunteer: fullName,
			// 		volunteerMobile: mobileNumber,
			// 	});
			// } catch (e) {
			// 	console.log('Mixpanel: ', e);
			// }
			dispatch({
				type: SAVE_BENE_RECORD,
				payload: {
					SACFormID,
					username,
					firstName,
					lastName,
					middleName,
					age,
					dob,
					programID,
					remarks,
					idNumber,
					region,
					province,
					municipality,
					barangay,
					cRegion,
					cProvince,
					cMunicipality,
					cBarangay,
					suffix,
					sex,
					ethnicity,
					occupation,
					sector,
					monthlyIncome,
					education,
					houseOwnership,
					healthCondition,
					program,
					nationalId,
					// reliefAssistance,
					volunteerName: fullName,
					volunteerMob: mobileNumber,
					dateCreated: epochtime,
					beneficiaryMobile,
					emailAddress,
					avatarPhoto,
					regType: '1',
				},
			});
			resolve('Validated');
		} else {
			dispatch({ type: SHOW_TOAST, payload: { text: 'Some fields are required' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	// console.log('onSubmitSuccess: ', props);
	currentState = {};
	dispatch({ type: SHOW_TOAST, payload: { text: 'New Record' } });
	props.navigation.goBack();
};

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

export const mapActionsToProps = (dispatch) => ({
	launchImagePicker(payload) {
		dispatch({ type: GET_ASSETS, payload });
	},
});


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

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