import '../../../shim.js';
import crypto from 'crypto';
import _ from 'lodash';
import React, { Component } from 'react';
import QRCode from 'react-native-qrcode-generator';
import { View, Dimensions, StyleSheet, Alert } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Text } from 'nixplay-ui-kit';

import i18n from '~/locale/i18n';
import { RESET_ALL_USERS, CHANGE_APP_ROOT } from '~/store/actionTypes';
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,
		backgroundColor: 'white',
	},
	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: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
	},
	mainText: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
		marginTop: 50,
	},
	reminder: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
		backgroundColor: basicColor.wrikeGreen2,
		marginHorizontal: 20,
		height: 60,
		paddingTop: 10,
		borderRadius: 8,
	},
	mainTagline: {
		flex: 0.4,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
	},
});


export class BasicUserDashboard 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,
		users: PropTypes.object.isRequired,
		resetAllUsers: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);

		// console.log('BASIC: ', props.users.currentUser);
		const { currentUser } = props.users;
		// const firstName = _.get(props.users.currentUser, 'firstName', '');
		// const lastName = _.get(props.users.currentUser, 'lastName', '');
		// const middleName = _.get(props.users.currentUser, 'middleName', '');
		// const fullName = `${firstName} ${middleName} ${lastName}`;
		// const fullNameVisible = `${lastName}, ${firstName} ${middleName.substr(0, 1).toUpperCase()}.`;
		const {
			barangay, municipality, username, fullName, memberRefId, dob, sex,
		} = props.users.currentUser;
		console.log('currentUser: ', props.users.currentUser);

		// mobileNumber, emailAddress
		// const username = (!_.isEmpty(mobileNumber) && mobileNumber.length >= 10) ? mobileNumber : emailAddress;
		// 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}.${formattedDOB}.${formattedSex}.${brgyCode}.${citymunCode}`;

		// const rawData = `${fullName}|${username}|${memberRefId}|${dob}|${age}|${sex}|${brgyCode}:${brgyDesc}|${citymunCode}:${citymunDesc}|${provCode}:${provDesc}|${regType}`;
		const proposeUserRefKey = this.encrypt(rawData);
		console.log('USER REF KEY: ', rawData, proposeUserRefKey);

		this.state = {
			proposeUserRefKey,
			// fullName,
			username,
			fullName,
		};
		this.props.navigation.setParams({
			onLogout: this.onLogout,
		});
	}

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

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

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

	decrypt = (text) => {
		const textParts = text.split(':');
		const iv = Buffer.from(textParts.shift(), 'hex');
		const encryptedText = Buffer.from(textParts.join(':'), 'hex');
		const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
		let decrypted = decipher.update(encryptedText);

		decrypted = Buffer.concat([decrypted, decipher.final()]);

		return decrypted.toString();
	}

	render() {
		const { fullName, username } = this.state;
		return (
			<View style={styles.container}>
				<View style={[styles.mainBg, { marginTop: 30 }]}>
					{/* <LanguageIcon /> */}
					<QRCode
						value={this.state.proposeUserRefKey}
						size={300}
						bgColor="black"
						fgColor="white"
					/>
				</View>
				<View style={styles.mainText}>
					<Text>{`Welcome ${fullName} - ${username}, As please present this QR code for claiming your assistance.`}</Text>
				</View>
				{/* <SafeAreaView style={styles.safeArea}>
					<View style={styles.reminder}>
						<Text style={{ color: 'white' }} textStyle="subhead">Reminder: Please connect to internet in order to help our system.</Text>
					</View>
				</SafeAreaView> */}
			</View>
		);
	}
}

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

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

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