/* eslint-disable prefer-destructuring */
import '../../../shim.js';
import crypto from 'crypto';
import _ from 'lodash';
import React, { Component } from 'react';
import { View, Alert } from 'react-native';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { Text } from 'nixplay-ui-kit';
import QRCodeScanner from 'react-native-qrcode-scanner';
import Mixpanel from 'react-native-mixpanel';

import i18n from '~/locale/i18n';
import { Button } from '~comp';
import { TextInput } from '~comp/reduxForm';
import { FIRST_TIME_INSTALL } from '~/lib/appConstants';

import { color } from '~/styles/variables'
import { SHOW_TOAST_ERROR, ADD_SCANNED_BENEFICIARY } from '~/store/actionTypes';
import { ERROR_INVALID } from '~/store/contentTypes';
import barangayList from '~/store/barangay.json';
import cityList from '~/store/municipality.json';
import provinceList from '~/store/provinces.json';
import regionList from '~/store/regions.json';

import { styles } from './styles';

const ENCRYPTION_KEY = 'MAAGAppDataCollectionAndDelivery'; // Must be 256 bits (32 characters)
let currentState = {};

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		// beneficiaries: PropTypes.object.isRequired,
		handleSubmit: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);

		this.state = { };

		this.debouncerHandleSubmit = _.debounce(this.props.handleSubmit, 3000, {
			leading: true,
			trailing: false,
		});

		// console.log('registration: ', this.props.registration);
		// USER REF KEY:  Paula Blanca Cordizar Alimbon|mejiamariano8.08@gmail.com|2eb18d30df4cd20607f7e2ed1c181747fe9ceb93|10-10-1988|32|Female|150708001:Caddayan|150708:AKBAR|150708:BASILAN|1
		// setTimeout(() => {
		// 	this.onSuccess({ data: '690298e9254d771db92ebf819803f14f:cb97a65eadb241e9508804e84a922bb6d18e3ad831fa9d037371cb06206b1849d44126ccd4ca783f1da4861efabfe5970bbc9dda2b95fc4e67b631438fb2bd23d397d1cbc09078d736ffdb19d4e22cc5' });
		// }, 5000);
	}

	onSuccess = (e) => {
		// console.log('onSuccess: ', e.data);
		if (!_.isEmpty(e.data)) {
			try {
				Mixpanel.track('scan_success');
				const encData = e.data;
				const decrypted = this.decrypt(encData);
				// console.log('decrypted: ', decrypted);
				const slicedItem = decrypted.split('.');
				// MEMBER REF ID
				const memberRefId = slicedItem[0];

				// NAME
				let firstName = [];
				let middleName = '';
				let lastName = [];
				let fullName = slicedItem[1].split('_');
				let middleIndex = 0;
				fullName.forEach((o, i) => {
					if (o.length === 1) {
						middleIndex = i;
						middleName = o;
					} else if (middleIndex > 0) {
						lastName.push(o);
					} else {
						firstName.push(o);
					}
				});
				firstName = firstName.join(' ');
				fullName = fullName.join(' ');
				lastName = lastName.join(' ');

				// USERNAME
				const username = `+63${slicedItem[2]}`;
				const dob = `${slicedItem[3].substr(0, 2)}/${slicedItem[3].substr(2, 2)}/${slicedItem[3].substr(4, 4)}`;
				let age = parseInt((new Date()).getFullYear(), 0) - parseInt(slicedItem[3].substr(4, 4), 0);
				const isNotDOBYet = (parseInt(slicedItem[3].substr(0, 2), 0) > parseInt((new Date()).getMonth(), 0));
				if (isNotDOBYet) {
					age -= 1;
				}
				const sex = slicedItem[4];

				// CURRENT ADDRESS
				const brgyCode = slicedItem[5];
				const { RECORDS: Barangays } = barangayList;
				const barangay = _.find(Barangays, (o) => (o.brgyCode === brgyCode));
				const brgyDescription = barangay.brgyDesc;
				const regCode = barangay.regCode;
				const { RECORDS: Regions } = regionList;
				const region = _.find(Regions, (o) => (o.regCode === regCode));
				const regDescription = region.regDesc;
				const citymunCode = barangay.citymunCode;
				const { RECORDS: Cities } = cityList;
				const city = _.find(Cities, (o) => (o.citymunCode === citymunCode));
				const citymunDescription = city.citymunDesc;
				const provCode = city.provCode;
				const { RECORDS: Provinces } = provinceList;
				const province = _.find(Provinces, (o) => (o.provCode === provCode));
				const provDescription = province.provDesc;

				const currentAddress = `${brgyDescription}, ${citymunDescription}, ${provDescription}, ${regDescription}`;

				// BIRTH PLACE ADDRESS
				const cCitymunCode = slicedItem[6];
				const cCity = _.find(Cities, (o) => (o.citymunCode === cCitymunCode));
				const cCitymunDescription = cCity.citymunDesc;
				const cProvCode = cCity.provCode;
				const cProvince = _.find(Provinces, (o) => (o.provCode === cProvCode));
				const cProvDescription = cProvince.provDesc;
				const cRegCode = cProvince.regCode;
				const cRegion = _.find(Regions, (o) => (o.regCode === cRegCode));
				const cRegDescription = cRegion.regDesc;

				const birthPlace = `${cCitymunDescription}, ${cProvDescription}, ${cRegDescription}`;

				const regType = 1;

				const routePage = () => {
					this.props.navigation.push(
						'SetScanTagAssistance',
						{
							encData,
							fullName,
							username,
							firstName,
							lastName,
							middleName,
							memberRefId,
							dob,
							age,
							sex,
							// brgyCode,
							// brgyDescription,
							// citymunCode,
							// citymunDescription,
							// provCode,
							// provDescription,
							// regCode,
							// regDescription,
							currentAddress,
							// cCitymunCode,
							// cCitymunDescription,
							// cProvCode,
							// cProvDescription,
							// cRegCode,
							// cRegDescription,
							birthPlace,
							regType,
						},
					);
				};
				Alert.alert(
					'MAAGApp - Details',
					`FullName: ${fullName}\nUsername: ${username}\nDate of Birth: ${dob}\nAge: ${age}\nSex: ${sex}\nMember Ref ID: ${memberRefId}\nBirth Place: ${birthPlace}\nCurrent Address: ${currentAddress}\nREG TYPE: ${regType}\n${parseInt(slicedItem[3].substr(0, 2), 0)} > ${parseInt((new Date()).getMonth(), 0)}`,
					[
						{
							text: 'Next',
							onPress: () => { routePage(); },
						},
					],
					{ cancelable: false },
				);
			} catch (error) {
				Mixpanel.track('scan_error');
				Alert.alert(
					'MAAGApp - Scanner ERROR',
					`DATA: ${e.data}, ${error.message}`,
					[
						{
							text: i18n.t('common.ok'),
							onPress: () => { this.props.navigation.goBack(); },
						},
					],
					{ cancelable: false },
				);
			}
			// console.log('Decrypted: ', decrypted);


		// 	// const { scannedUsers } = this.props.beneficiaries;
		// 	// // check if exist
		// 	// const item = _.find(scannedUsers, ['bMemberRefId', memberRefId]);
		// 	// const isExistDate = (!_.isEmpty(item))
		// 	// 	? ((new Date(item.datetime * 1000)).getDate() === (new Date()).getDate()) : false;
		// 	// const dateCreated = (isExistDate) ? (new Date(item.datetime * 1000)) : 'n/a';
		} else {
			// rescan again
			Alert.alert(
				'MAAGpp - Scanner',
				'Please try to re-start again to get beneficiary information',
				[
					{
						text: i18n.t('common.ok'),
						onPress: () => { this.props.navigation.goBack(); },
					},
				],
				{ cancelable: false },
			);
		}
	};

	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() {
		return (
			<View style={styles.container}>
				{/* <View style={styles.inputContainer}>
					<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 50 }}>SCAN</Text>
				</View> */}
				<QRCodeScanner
					onRead={this.onSuccess}
					// flashMode={QRCodeScanner.Constants.FlashMode.torch}
					topContent={
						<Text textStyle="subhead" style={{ textAlign: 'center', marginBottom: 50 }}>Beneficiary QRCode</Text>
					}
					renderCameraMarker
					// bottomContent={}
				/>
				{/* <View style={styles.checkboxContainer}>
					<View style={styles.checkboxLabel}>
						<Text style={{ color, paddingHorizontal: 18 }} textStyle="subhead">Your password must have at least 8 combined letters, numbers, symbols (like ! and %).</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="Next"
							style={[styles.button, styles.loginButton]}
							onPress={this.debouncerHandleSubmit}
							disabled={hasError}
							text={i18n.t('common.next')} />
					</View>
				</SafeAreaView> */}
			</View>
		);
	}
}

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

const FormContainer = reduxForm({
	form: 'ScanQR',
	destroyOnUnmount: false,
})(ScanQR);

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