import '../../shim.js';
import crypto from 'crypto';
import _ from 'lodash';
import Mixpanel from 'react-native-mixpanel';
import {
	RESET_ALL_BENEFICIARIES,
	ADD_SCANNED_BENEFICIARY,
	// ADD_TAGGED_TO_PROGRAM,
	UPDATE_SYNC_DATA,
	// CHECK_IF_EXIST_BENEFICIARY,
	SAVE_BENE_RECORD,
	ADD_BENE_MEMBER_RECORD,
	GET_ALL_BENEFICIARIES,
	EDIT_BENE_RECORD,
	EDIT_BENE_MEMBER_RECORD,
	REQUEST_VALIDATE_ASSISTANCE,
	REQUEST_VALIDATE_ASSISTANCE_SUCCESS,
	REQUEST_VALIDATE_ASSISTANCE_ERROR,
	ADD_SCANNED_BENEFICIARY_OFFLINE,
	REQUEST_VERIFY_REFID,
	REQUEST_VERIFY_REFID_SUCCESS,
	REQUEST_VERIFY_REFID_ERROR,
} from '~/store/actionTypes';

const beneficiaryInit = {
	scannedUsers: [], // list of users got logged in
	alreadySync: [],
	pendingSync: [],
	manualBeneSave: [],
	manualBeneMemberSave: [],
	meta: {
		loading: false,
		error: '',
	},
	lastSyncDateTime: '',
	lastScanDateTime: '',
	lastScanUser: '',
	lastManualSaveDateTime: '',
	lastScanProvince: {},
	lastScanMunicipality: {},
	lastScanBarangay: {},
};


const updateRecords = (state, payload) => {
	const updateRecordsList = [];
	if (!_.isEmpty(state.manualBeneSave)) {
		state.manualBeneSave.forEach((item) => {
			if (!_.isEmpty(item)) {
				let updatedItem = item;
				if (payload.memberRefId === item.memberRefId && payload.dateCreated === item.dateCreated) {
					updatedItem = {
						...updatedItem,
						...payload,
					};
				}
				updateRecordsList.push(updatedItem);
			}
		});
		return {
			...state,
			manualBeneSave: updateRecordsList,
		};
	}
	return state;
};

const updateMemberRecords = (state, payload) => {
	const { manualBeneMemberSave } = state;
	const memberList = (_.has(manualBeneMemberSave, payload.memberRefId)) ? manualBeneMemberSave[`${payload.memberRefId}`] : [];
	if (!_.isEmpty(memberList)) {
		let isMatch = false;
		memberList.forEach((item) => {
			if (!isMatch && (item.memberId === payload.memberId)) {
				isMatch = true;
				_.set(item, 'lastName', payload.lastName);
				_.set(item, 'firstName', payload.firstName);
				_.set(item, 'middleName', payload.middleName);
				_.set(item, 'dob', payload.dob);
				_.set(item, 'age', payload.age);
				_.set(item, 'mobileNumber', payload.mobileNumber);
				_.set(item, 'emailAddress', payload.emailAddress);
				_.set(item, 'familyPosition', payload.familyPosition);
				_.set(item, 'avatarPhoto', payload.avatarPhoto);
				_.set(item, 'sex', payload.sex);
				_.set(item, 'occupation', payload.occupation);
				_.set(item, 'remarks', payload.remarks);
				_.set(item, 'healthCondition', payload.healthCondition);
				_.set(item, 'sector', payload.sector);
				_.set(item, 'monthlyIncome', payload.monthlyIncome);
				_.set(item, 'education', payload.education);
			}
		});
		manualBeneMemberSave[`${payload.memberRefId}`] = memberList;
		return {
			...state,
			manualBeneMemberSave: { ...manualBeneMemberSave },
		};
	}
	return state;
};


export const beneficiaries = (state = beneficiaryInit, { type, payload }) => {
	switch (type) {
		case ADD_SCANNED_BENEFICIARY: {
			return {
				...state,
				// scannedUsers: [payload, ...state.scannedUsers],
				// lastScanDateTime: Math.floor(new Date().getTime() / 1000.0),
				// lastScanUser: payload,
				lastScanProvince: payload.province,
				lastScanMunicipality: payload.municipality,
				lastScanBarangay: payload.barangay,
			};
		}
		case ADD_SCANNED_BENEFICIARY_OFFLINE: {
			Mixpanel.trackWithProperties('scanned_assistance_offline', { ...payload });
			return {
				...state,
				scannedUsers: _.compact([payload, ...state.scannedUsers]),
				lastScanDateTime: Math.floor(new Date().getTime() / 1000.0),
				lastScanUser: payload,
			};
		}
		case SAVE_BENE_RECORD: {
			const memberRefId = crypto.randomBytes(10).toString('hex').toUpperCase();
			const insertItem = { ...payload, memberRefId };
			// mixpanel
			Mixpanel.trackWithProperties('add_beneficiary', { ...insertItem });
			return {
				...state,
				manualBeneSave: [insertItem, ...state.manualBeneSave],
				lastManualSaveDateTime: Math.floor(new Date().getTime() / 1000.0),
			};
		}
		case EDIT_BENE_RECORD:
			return updateRecords(state, payload);
		case EDIT_BENE_MEMBER_RECORD:
			return updateMemberRecords(state, payload);
		case ADD_BENE_MEMBER_RECORD: {
			const { manualBeneMemberSave } = state;
			const memberId = crypto.randomBytes(10).toString('hex');
			const insertItem = { ...payload, memberId };
			const arrValues = (_.has(manualBeneMemberSave, payload.memberRefId)) ? manualBeneMemberSave[`${payload.memberRefId}`] : [];
			manualBeneMemberSave[`${payload.memberRefId}`] = _.compact([insertItem, ...arrValues]);
			// mixpanel
			Mixpanel.trackWithProperties('household_member', { ...insertItem });
			return {
				...state,
				manualBeneMemberSave: { ...manualBeneMemberSave },
				lastUpdate: Math.floor(new Date().getTime() / 1000.0),
			};
		}
		case REQUEST_VALIDATE_ASSISTANCE: {
			return {
				...state,
				meta: { ...state.meta, loading: true, error: '' },
			};
		}
		case REQUEST_VALIDATE_ASSISTANCE_SUCCESS: {
			// mixpanel
			Mixpanel.trackWithProperties('scanned_assistance', { ...payload });
			return {
				...state,
				meta: { ...state.meta, loading: false },
				scannedUsers: _.uniq([payload, ...state.scannedUsers]),
				lastScanDateTime: Math.floor(new Date().getTime() / 1000.0),
				lastScanUser: payload,
				// lastScanProvince: payload.province,
				// lastScanMunicipality: payload.municipality,
				// lastScanBarangay: payload.barangay,
			};
		}
		case REQUEST_VALIDATE_ASSISTANCE_ERROR: {
			// mixpanel
			Mixpanel.track('scanned_assistance_error');
			return {
				...state,
				meta: { ...state.meta, loading: false, error: payload.error },
			};
		}
		// case ADD_TAGGED_TO_PROGRAM:
		// 	return state;
		case UPDATE_SYNC_DATA:
			return state;
		case GET_ALL_BENEFICIARIES:
			return state;
		case RESET_ALL_BENEFICIARIES: {
			return beneficiaryInit;
		}
		case REQUEST_VERIFY_REFID: {
			return {
				...state,
				meta: { ...state.meta, loading: true, error: '' },
			};
		}
		case REQUEST_VERIFY_REFID_SUCCESS: {
			// mixpanel
			Mixpanel.trackWithProperties('verify_benefit_refid', { ...payload });
			return {
				...state,
				meta: { ...state.meta, loading: false },
			};
		}
		case REQUEST_VERIFY_REFID_ERROR: {
			// mixpanel
			Mixpanel.track('verify_benefit_refid_error');
			return {
				...state,
				meta: { ...state.meta, loading: false, error: payload.error },
			};
		}
		default:
			return state;
	}
};
