import '../../../shim.js';
import crypto from 'crypto';
import _ from 'lodash';
import React, { Component } from 'react';
import QRCode from 'react-native-qrcode-generator';
import { SafeAreaView, View, Dimensions, StyleSheet, Alert } from 'react-native';
import DefaultPreference from 'react-native-default-preference';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Text } from 'nixplay-ui-kit';
import Geolocation from '@react-native-community/geolocation';
import OpenAppSettings from 'react-native-app-settings';

import i18n from '~/locale/i18n';
import { FIRST_TIME_INSTALL } from '~/lib/appConstants';
import { RESET_ALL_USERS, CHANGE_APP_ROOT, UPDATE_LOCATION_COORDINATES } from '~/store/actionTypes';
import { Button } from '~comp';
import { color as basicColor } from '~/styles/variables';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
const ENCRYPTION_KEY = 'MAAGAppDataCollectionAndDelivery'; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16

export const styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'column',
		backgroundColor: 'white',
		position: 'relative',
		height: screenHeight,
		width: screenWidth,
	},
	pager: {
		width: screenWidth,
		height: screenHeight,
	},
	slideContainer: {
		flex: 1,
	},
	image: {
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
	},
	textContainer: {
		flex: 1,
		justifyContent: 'center',
		paddingHorizontal: 36,
	},
	textTitle: {
		fontSize: 27,
		marginTop: 21,
		marginBottom: 16,
	},
	safeArea: {
		position: 'absolute',
		bottom: 20,
		width: '100%',
	},
	buttonContainer: {
		flexDirection: 'column',
		paddingHorizontal: 18,
		paddingTop: 25,
		paddingBottom: 14,
	},
	button: {
		borderRadius: 4,
	},
	signupButton: {
		marginRight: 0,
		backgroundColor: basicColor.wrikeGreen2,
	},
	loginButton: {
		marginTop: 8,
		backgroundColor: basicColor.wrikeBg,
	},
	pagerDots: {
		flexDirection: 'row',
		justifyContent: 'center',
	},
	dots: {
		width: 8,
		height: 8,
		borderRadius: 4,
		marginHorizontal: 4,
	},
	mainBg: {
		justifyContent: 'center',
		height: screenWidth - 30,
		width: screenWidth - 50,
		alignSelf: 'center',
	},
	mainText: {
		paddingHorizontal: 18,
	},
	reminder: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
		backgroundColor: basicColor.wrikeGreen2,
		marginHorizontal: 20,
		height: 60,
		paddingTop: 10,
		borderRadius: 8,
	},
	form: {
		flex: 1,
	},
});


export class SocialWorkerDashboard extends Component {
	static navigationOptions = ({ navigation }) => {
		const leftButtons = [];
		const { getParam } = navigation;
		return {
			headerTransparent: false,
			title: '',
			subtitle: '',
			hideBackButton: true,
			leftButtons,
			rightButtons: [{
				onPress: () => { getParam('onLogout')(); },
				icon: 'user',
			}],
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		isConnected: PropTypes.bool.isRequired,
		users: PropTypes.object.isRequired,
		resetAllUsers: PropTypes.func.isRequired,
		updateLocation: PropTypes.func.isRequired,
		// beneficiaries: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props);

		// console.log('BASIC: ', props.users.currentUser);
		const { currentUser } = props.users;
		// if (!_.isEmpty(props.users.currentUser)) {
		const {
			fullName,
			// mobileNumber,
			barangay,
			municipality,
			// province,
			// password,
			// damage,
			// household,
			// program,
			username,
			memberRefId,
		} = currentUser;
		// barangay
		const brgyCode = _.has(currentUser, 'brgyCode') ? currentUser.brgyCode : barangay.brgyCode;
		// const brgyDesc = _.has(currentUser, 'brgyCode') ? barangay : barangay.brgyDesc;

		// municipality
		const citymunCode = _.has(currentUser, 'citymunCode') ? currentUser.citymunCode : municipality.citymunCode;
		// const citymunDesc = _.has(currentUser, 'citymunCode') ? municipality : municipality.citymunDesc;

		// province
		// const provCode = _.has(currentUser, 'provCode') ? currentUser.citymunCode : province.provCode;
		// const provDesc = _.has(currentUser, 'provCode') ? province : province.provDesc;

		// const formattedSex = (!_.isEmpty(sex)) ? sex.toUpperCase().charAt(0) : '';
		// const formattedDOB = (!_.isEmpty(dob)) ? dob.split('-').join('') : '';
		const formattedUsername = (!_.isEmpty(username)) ? username.replace('+63', '') : '';

		const rawData = `${memberRefId}.${fullName}.${formattedUsername}...${brgyCode}.${citymunCode}`;

		// const rawData = `${fullName}|${mobileNumber}|${password}|${household}|${damage}|${program}|${brgyCode}:${brgyDesc}|${citymunCode}:${citymunDesc}|${provCode}:${provDesc}`;
		const proposeUserRefKey = this.encrypt(rawData);

		this.state = {
			proposeUserRefKey: (!_.isEmpty(proposeUserRefKey)) ? proposeUserRefKey : '',
			fullName: (!_.isEmpty(fullName)) ? fullName : '',
			username: (!_.isEmpty(username)) ? username : memberRefId,
		};

		DefaultPreference.set(FIRST_TIME_INSTALL, '');
		this.debouncerGoToList = _.debounce(this.goToList, 100, {
			leading: true,
			trailing: false,
		});
		this.debouncerScanQRCode = _.debounce(this.scanQRCode, 100, {
			leading: true,
			trailing: false,
		});
		// this.debouncerAddRecord = _.debounce(this.addRecord, 100, {
		// 	leading: true,
		// 	trailing: false,
		// });
		this.debouncerScannedRecords = _.debounce(this.goToScannedRecords, 100, {
			leading: true,
			trailing: false,
		});
		this.debouncerPendingPrograms = _.debounce(this.goToPendingBeneProgram, 100, {
			leading: true,
			trailing: false,
		});
		this.debouncerVerifyREFID = _.debounce(this.goToVerifyRefID, 100, {
			leading: true,
			trailing: false,
		});
		this.props.navigation.setParams({
			onLogout: this.onLogout,
		});
	}

	componentDidMount() {
		if (!_.isEmpty(Geolocation)) {
			// ios
			Geolocation.getCurrentPosition(
				position => {
					const coordinates = JSON.stringify(position);
					this.props.updateLocation(coordinates);
				},
				(error) => {
					if (error.code === 1) {
						Alert.alert(
							'MAAGApp - Location',
							'Please allow MAAGApp to use your Location Service.',
							[
								{ text: i18n.t('common.cancel'), onPress: () => {}, style: 'cancel' },
								{
									text: 'Settings',
									onPress: () => {
										OpenAppSettings.open();
									},
								},
							],
							{ cancelable: false },
						);
					}
				},
				{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
			);
			// android
			Geolocation.watchPosition(position => {
				const coordinates = JSON.stringify(position);
				this.props.updateLocation(coordinates);
			});
		}
	}

	onLogout = () => {
		this.showAlert(
			'MAAGApp',
			'Do you want to proceed logout?',
			() => { },
			() => { this.props.resetAllUsers(); },
		);
	}

	onStartShouldSetResponder = (evt) => {
		if (evt.nativeEvent.touches.length >= 2) {
			return true;
		}
		return false;
	}

	onResponderRelease = () => {
		this.props.navigation.push('ReleaseNotes');
	}

	encrypt = (text) => {
		const iv = crypto.randomBytes(IV_LENGTH);
		const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
		let encrypted = cipher.update(text);
		encrypted = Buffer.concat([encrypted, cipher.final()]);
		return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
	}

	goToList = () => {
		this.props.navigation.push('BeneficiaryList');
	}

	goToScannedRecords = () => {
		this.props.navigation.push('ScannedAssistanceList');
	}

	goToVerifyRefID = () => {
		this.props.navigation.push('VerifyBenefitRefID');
	}

	goToPendingBeneProgram = () => {
		this.props.navigation.push('ScannedAssistanceList');
	}

	scanQRCode = () => {
		this.props.navigation.push('ScanQR');
	}

	addRecord = () => {
		this.props.navigation.push('AddBeneficiaryRecord', { fullName: this.state.fullName, mobileNumber: this.state.mobileNumber });
	}

	showAlert = (title, msg, callbackCancel, callbackContinue) => {
		Alert.alert(
			title,
			msg,
			[
				{
					text: i18n.t('common.cancel'),
					onPress: callbackCancel ? () => { callbackCancel(); } :
						() => {},
				},
				{
					text: i18n.t('common.continue'),
					onPress: callbackContinue ? () => { callbackContinue(); } :
						() => {},
				},
			],
			{ cancelable: false },
		);
	}

	render() {
		const { fullName, username } = this.state;
		return (
			<View style={styles.container}>
				<View
					style={styles.mainBg}
					onStartShouldSetResponder={this.onStartShouldSetResponder}
					onResponderRelease={this.onResponderRelease}
				>
					<QRCode
						value={this.state.proposeUserRefKey}
						size={screenWidth - 50}
						bgColor={basicColor.wrikeBg}
						fgColor="white"
					/>
				</View>
				<View style={styles.mainText}>
					<Text style={{ paddingHorizontal: 20, marginTop: 20, marginBottom: 30 }}>{`Welcome Administering Officer: ${fullName} - ${username}.`}</Text>
					<Button
						testID="GoToRecords"
						onPress={this.debouncerGoToList}
						// type="link"
						color="green"
						text="Beneficiary Records"
						setNumberOfLines={1}
					/>
					{/* <Button
						testID="ScanQRRecords"
						onPress={this.debouncerScannedRecords}
						type="link"
						color="green"
						text="Scanned Assistance Records"
						setNumberOfLines={1}
						style={{ marginTop: 30 }}
					/> */}
					<Button
						testID="ScanQR"
						onPress={this.debouncerScanQRCode}
						// type="link"
						color="green"
						text="Scan QR Code"
						setNumberOfLines={1}
						style={{ marginTop: 10 }}
					/>
					<Button
						testID="Verify Assistance REFID"
						onPress={this.debouncerVerifyREFID}
						// type="link"
						color="green"
						text="Verify Benefit REF-ID"
						setNumberOfLines={1}
						style={{ marginTop: 10 }}
					/>
					{/* <Button
						testID="GoToRecords"
						onPress={this.debouncerPendingPrograms}
						type="link"
						color="green"
						text="Pending Program Applications"
						setNumberOfLines={1}
					/> */}
					{/* <Button
						testID="AddRecord"
						onPress={this.debouncerAddRecord}
						type="link"
						color="green"
						text="Add Beneficiary Record"
						setNumberOfLines={1}
						style={{ marginTop: 30 }}
					/> */}
				</View>
				<View style={styles.form} />
				{ (!this.props.isConnected) &&
					<SafeAreaView style={styles.safeArea}>
						<View style={[styles.reminder, { backgroundColor: basicColor.wrikeBg }]}>
							<Text style={{ color: 'white' }} textStyle="subhead">Reminder: Please maintain connected to internet in order to help our system.</Text>
						</View>
					</SafeAreaView>
				}
			</View>
		);
	}
}

const mapStateToProps = (state) => ({
	isConnected: state.network.isConnected,
	users: state.users,
	beneficiaries: state.beneficiaries,
});

const mapActionsToProps = (dispatch) => ({
	resetAllUsers() {
		dispatch({ type: RESET_ALL_USERS, payload: {} });
		dispatch({ type: CHANGE_APP_ROOT, payload: { root: 'login' } });
	},
	updateLocation(payload) {
		dispatch({ type: UPDATE_LOCATION_COORDINATES, payload });
	},
});

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