import _ from 'lodash';
import React, { Component } from 'react';
import { SafeAreaView, View, Keyboard, Platform, ActivityIndicator, ScrollView } 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 QRCode from 'react-native-qrcode-generator';

import { Text, color } 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, ADD_SCANNED_BENEFICIARY_OFFLINE, REQUEST_VALIDATE_ASSISTANCE, ADD_SCANNED_BENEFICIARY } from '~/store/actionTypes';

import { styles } from './styles';

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

export class SetScanTagAssistance extends Component {
	static navigationOptions = ({ navigation }) => {
		const { getParam } = navigation;
		const leftButtons = [];
		const rightButtons = [];
		return {
			headerTransparent: false,
			title: getParam('fullName', 'Tagging'),
			subtitle: getParam('subtitle', 'Relief Assitance'),
			hideBackButton: true,
			leftButtons,
			rightButtons,
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.isRequired,
		beneficiaries: PropTypes.object.isRequired,
		isLoading: PropTypes.bool.isRequired,
		users: PropTypes.object.isRequired,
		currentLocation: PropTypes.any.isRequired,
	}

	constructor(props) {
		super(props);
		currentState = {};
		const { currentUser } = props.users;
		// recent field location of relief
		const province = _.get(props.beneficiaries, 'lastScanProvince', {});
		const municipality = _.get(props.beneficiaries, 'lastScanMunicipality', {});
		const barangay = _.get(props.beneficiaries, 'lastScanBarangay', {});

		const { getParam } = this.props.navigation;

		// beneficiary data
		const bRegType = getParam('regType', '');
		const bEncData = getParam('encData', '');
		const bFullName = getParam('fullName', '');
		const bFirstName = getParam('firstName', '');
		const bMiddleName = getParam('middleName', '');
		const bLastName = getParam('lastName', '');
		const bMemberRefId = getParam('memberRefId', 'null');
		const bUsername = getParam('username', '');
		const bDob = getParam('dob', '');
		const bAge = getParam('age', 'null');
		const bSex = getParam('sex', '');
		const bCurrentAddress = getParam('currentAddress', 'null');
		const bBirthPlace = getParam('birthPlace', 'null');

		currentState = {
			...currentState,
			bRegType,
			bEncData,
			bFullName,
			bFirstName,
			bMiddleName,
			bLastName,
			bUsername,
			bDob,
			bAge,
			bSex,
			bCurrentAddress,
			bBirthPlace,
			bMemberRefId,
			province, // relief location
			municipality, // relief location
			barangay, // relief location
			scanByUsername: _.get(currentUser, 'username', 'null'),
			scanByName: _.get(currentUser, 'fullName', 'null'),
			scanByMemberRefId: _.get(currentUser, 'memberRefId', 'null'),
			isAnimating: false,
			bankError: false,
			accountInfoError: false,
		};
		// console.log(currentState);
		this.state = {
			province,
			municipality,
			barangay,
			taggedAssistance: [],
			scannedData: bMemberRefId,
			bottomOpacity: 1,
			fullName: bFullName,
			username: (!_.isEmpty(bUsername)) ? bUsername : bMemberRefId,
			bankName: '',
			accountInfo: '', // either mobile number or bank account number
			disbursementMode: '',
		};

		this.debouncerHandleSubmit = _.debounce(this.props.handleSubmit, 3000, {
			leading: true,
			trailing: false,
		});
		this.props.navigation.setParams({
			fullName: this.state.fullName,
			subtitle: 'Relief Assitance - Case #1102',
		});
		// console.log('current location: ', this.props.currentLocation);
		// Alert.alert(
		// 	'MAAGApp - Location',
		// 	`Current Location: ${JSON.stringify(location.coords)}`,
		// 	[
		// 		{
		// 			text: 'OK',
		// 			onPress: () => { },
		// 		},
		// 	],
		// 	{ cancelable: 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 });
	};

	onUpdateAssistance = (taggedAssistance) => {
		if (taggedAssistance.join().indexOf('Cash Transfer') >= 0) {
			this.setState({ taggedAssistance });
			currentState = { ...currentState, taggedAssistance };
		} else {
			this.setState({ taggedAssistance, disbursementMode: '', bankName: '', accountInfo: '' });
			currentState = {
				...currentState, taggedAssistance, disbursementMode: '', bankName: '', accountInfo: '',
			};
		}
	}

	reliefAssistanceSelect = () => {
		this.props.navigation.push('ReliefMultiSelection', { selected: this.state.taggedAssistance.join(), onUpdate: this.onUpdateAssistance });
	}

	onUpdateDisbursement = (mode) => {
		this.setState({ disbursementMode: mode });
		currentState = { ...currentState, disbursementMode: mode };
	}

	disbursementModeSelect = () => {
		this.props.navigation.push('DisbursementModeSelection', { selected: this.state.disbursementMode, onUpdate: this.onUpdateDisbursement });
	}


	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, taggedAssistance, disbursementMode,
			bankName, accountInfo,
		} = this.state;
		const visibleReliefAssistance = (!_.isEmpty(taggedAssistance)) ? `(${taggedAssistance.length}) - ${taggedAssistance.join()}` : '';
		const bankColor = (currentState.bankError) ? color.red : color.borderMistBlue;
		const accountInfoColor = (currentState.accountInfoError) ? color.red : color.borderMistBlue;
		return (
			<View style={[styles.container]}>
				<ScrollView
					style={{
						flex: 1,
						flexDirection: 'column',
						height: '100%',
						width: '100%',
					}}
					contentContainerStyle={styles.contentContainer}
					showsVerticalScrollIndicator={false}
					showsHorizontalScrollIndicator={false}
				>
					<View style={[styles.inputContainer]}>
						<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: 0 }]}>
							<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: 0 }]}>
							<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.inputContainer, { marginTop: 0 }]}>
						<Text style={styles.inputElement} textStyle="subhead">Tag Relief Assistance</Text>
						<CustomPicker
							action={this.reliefAssistanceSelect}
							itemSelected={visibleReliefAssistance}
							name="Assistance"
							placeholder="Select Relief Assistance"
						/>
					</View>
					{ (!_.isEmpty(visibleReliefAssistance) && visibleReliefAssistance.indexOf('Cash Transfer') >= 0) &&
						<View style={[styles.inputContainer, { marginTop: 0 }]}>
							<Text style={styles.inputElement} textStyle="subhead">Disbursement Option</Text>
							<CustomPicker
								action={this.disbursementModeSelect}
								itemSelected={disbursementMode}
								name="Disbursement"
								placeholder="Select Mode of Gateway"
								hasError={currentState.disbursementError}
							/>
						</View>
					}
					{ (!_.isEmpty(disbursementMode) && disbursementMode.indexOf('Other') >= 0) &&
						<View style={[styles.inputContainer, { marginTop: -5 }]}>
							<Text
								style={[styles.inputElement, { marginTop: 0 }]}
								textStyle="subhead"
							>
								Other Bank Name
							</Text>
							<TextInput
								name="bankName"
								testID="tiBankName"
								placeholder="Bank Name"
								autoCapitalize="none"
								autoCorrect={false}
								maxLength={10}
								returnKeyType="next"
								keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
								blurOnSubmit
								onSubmitEditing={this.debouncerHandleSubmit}
								style={{ borderColor: bankColor }}
								selectionColor={basicColor.wrikeGreen2}
								defaultText={bankName}
								onChange={text => {
									this.setState({ bankName: text });
									currentState = { ...currentState, bankName: text };
								}}
							/>
						</View>
					}
					{ (!_.isEmpty(disbursementMode)) &&
						<View style={[styles.inputContainer, { marginTop: -15 }]}>
							<Text
								style={[styles.inputElement, { marginTop: 0 }]}
								textStyle="subhead"
							>
								Account or Mobile Number
							</Text>
							<TextInput
								name="accountInfo"
								testID="tiAccountInfo"
								placeholder="Account or Mobile Number"
								autoCapitalize="none"
								autoCorrect={false}
								returnKeyType="next"
								keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
								blurOnSubmit
								onSubmitEditing={this.debouncerHandleSubmit}
								style={{ borderColor: accountInfoColor }}
								selectionColor={basicColor.wrikeGreen2}
								defaultText={accountInfo}
								onChange={text => {
									this.setState({ accountInfo: text });
									currentState = { ...currentState, accountInfo: text };
								}}
							/>
						</View>
					}
					<View style={[styles.checkboxContainer, { flexDirection: 'column' }]}>
						<QRCode
							value={this.state.scannedData}
							size={150}
							fgColor="white"
						/>
						<Text textStyle="subhead" style={{ textAlign: 'center', marginVertical: 10 }}>{this.state.username}</Text>
					</View>
					{ (this.props.isLoading) &&
						<View style={styles.indicator}>
							<ActivityIndicator size="large" color={basicColor.wrikeGreen2} style={{ alignSelf: 'center' }} />
						</View>
					}
				</ScrollView>
				<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}
							text="Save Record"
						/>
					</View>
				</SafeAreaView>
			</View>
		);
	}
}

const onSubmit = (values, dispatch, props) => (
	new Promise((resolve, reject) => {
		const {
			bRegType,
			bFirstName,
			bMiddleName,
			bLastName,
			bCurrentAddress,
			bBirthPlace,
			bDob,
			bAge,
			bSex,
			bFullName,
			bUsername,
			bMemberRefId,
			barangay,
			municipality,
			province,
			taggedAssistance,
			bEncData,
			scanByUsername,
			scanByName,
			scanByMemberRefId,
			bankName,
			accountInfo,
			disbursementMode,
		} = currentState;
		const location = (!_.isEmpty(props.currentLocation)) ? JSON.parse(props.currentLocation) : '';
		const callAPI = () => {
			checkInternetConnection().then(isConnected => {
				if (isConnected) {
					dispatch({
						type: REQUEST_VALIDATE_ASSISTANCE,
						payload: {
							bFirstName: !_.isEmpty(bFirstName) ? bFirstName : 'null',
							bMiddleName: !_.isEmpty(bMiddleName) ? bMiddleName : 'null',
							bLastName: !_.isEmpty(bLastName) ? bLastName : 'null',
							bCurrentAddress: !_.isEmpty(bCurrentAddress) ? bCurrentAddress : 'null',
							bBirthPlace: !_.isEmpty(bBirthPlace) ? bBirthPlace : 'null',
							dob: !_.isEmpty(bDob) ? bDob : 'null',
							age: bAge,
							sex: !_.isEmpty(bSex) ? bSex : 'null',
							fullName: bFullName,
							username: bUsername,
							memberRefId: !_.isEmpty(bMemberRefId) ? bMemberRefId : 'null',
							barangay: !_.isEmpty(barangay.brgyDesc) ? barangay.brgyDesc : 'null',
							brgyCode: !_.isEmpty(barangay.brgyCode) ? barangay.brgyCode : 'null',
							municipality: municipality.citymunDesc,
							citymunCode: municipality.citymunCode,
							province: province.provDesc,
							provCode: province.provCode,
							taggedAssistance: taggedAssistance.join(),
							regType: bRegType,
							encData: bEncData,
							scanByUsername,
							scanByName,
							scanByMemberRefId,
							bankName: !_.isEmpty(bankName) ? bankName : 'null',
							accountInfo: !_.isEmpty(accountInfo) ? accountInfo : 'null',
							disbursementMode: !_.isEmpty(disbursementMode) ? disbursementMode : 'null',
							geoTag: !_.isEmpty(location) ? JSON.stringify(location) : 'null',
							resolve,
							reject,
						},
					});
				} else {
					// save offline data
					// dispatch({
					// 	type: ADD_SCANNED_BENEFICIARY_OFFLINE,
					// 	payload: {
					// 		firstName: bFirstName,
					// 		middleName: bMiddleName,
					// 		lastName: bLastName,
					// 		currentAddress: bCurrentAddress,
					// 		birthPlace: bBirthPlace,
					// 		dob: bDob,
					// 		age: bAge,
					// 		sex: bSex,
					// 		fullName: bFullName,
					// 		username: bUsername,
					// 		memberRefId: bMemberRefId,
					// 		barangay: barangay.brgyDesc,
					// 		brgyCode: barangay.brgyCode,
					// 		municipality: municipality.citymunDesc,
					// 		citymunCode: municipality.citymunCode,
					// 		province: province.provDesc,
					// 		provCode: province.provCode,
					// 		taggedAssistance: taggedAssistance.join(),
					// 		regType: bRegType,
					// 		encData: bEncData,
					// 		scanByUsername,
					// 		scanByName,
					// 		scanByMemberRefId,
					// 		bankName: !_.isEmpty(bankName) ? bankName : 'null',
					// 		accountInfo: !_.isEmpty(accountInfo) ? accountInfo : 'null',
					// 		disbursementMode: !_.isEmpty(disbursementMode) ? disbursementMode : 'null',
					// 		geoTag: !_.isEmpty(location) ? JSON.stringify(location) : 'null',
					// 	},
					// });
					// resolve({ message: 'Created scanned assistance', status: '201' });
					dispatch({ type: SHOW_TOAST, payload: { text: 'No Network Connection.' } });
				}
			});
		};
		// account or mobile number
		if (_.isEmpty(accountInfo) && !_.isEmpty(taggedAssistance) && taggedAssistance.join().indexOf('Cash Transfer') >= 0) {
			currentState = { ...currentState, accountInfoError: true };
		} else {
			currentState = { ...currentState, accountInfoError: false };
		}
		// disbursement mode
		if (_.isEmpty(disbursementMode) && !_.isEmpty(taggedAssistance) && taggedAssistance.join().indexOf('Cash Transfer') >= 0) {
			currentState = { ...currentState, disbursementError: true };
		} else {
			currentState = { ...currentState, disbursementError: false };
		}
		// bankError
		if (_.isEmpty(bankName) && !_.isEmpty(disbursementMode) && disbursementMode.indexOf('Other') >= 0
			&& !_.isEmpty(taggedAssistance) && taggedAssistance.join().indexOf('Cash Transfer') >= 0) {
			currentState = { ...currentState, bankError: true };
		} else {
			currentState = { ...currentState, bankError: false };
		}
		if (!_.isEmpty(province) && !_.isEmpty(municipality)
			&& !_.isEmpty(barangay) && !_.isEmpty(taggedAssistance)
			&& !currentState.accountInfoError && !currentState.disbursementError) {
			// console.log('Validated: ', currentState);
			dispatch({
				type: ADD_SCANNED_BENEFICIARY,
				payload: {
					barangay,
					municipality,
					province,
				},
			});
			callAPI();
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Some fields are required' } });
			reject();
		}
	})
);

const onSubmitSuccess = (result, dispatch, props) => {
	if (_.has(result, 'message')) {
		if (_.isEqual(result.message, 'Created scanned assistance') || _.isEqual(result.status, '201')) {
			currentState = {};
			dispatch({ type: SHOW_TOAST, payload: { text: 'New Scanned Record' } });
		} else {
			dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'User Already Given Relief!' } });
		}
		props.navigation.pop(2);
	} else {
		// bad gateway
		dispatch({ type: SHOW_TOAST_ERROR, payload: { text: 'Bad Gateway' } });
	}
};

const mapStateToProps = (state) => ({
	isLoggedIn: !_.isEmpty(state.user.token),
	languageCode: _.get(state, 'settings.languageCode'),
	beneficiaries: state.beneficiaries,
	isLoading: state.beneficiaries.meta.loading,
	users: state.users,
	currentLocation: state.app.config,
});

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

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

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