import _ from 'lodash';
import React, { Component } from 'react';
import {
	View,
	FlatList,
	TouchableOpacity,
	BackHandler,
} from 'react-native';
import { connect } from 'react-redux';
import {
	Text,
	Avatar,
	ActionSheet,
	ContentGridEmpty,
} from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import i18n from '~/locale/i18n';
import { color as basicColor } from '~/styles/variables';
import { styles } from './styles';
// import { RESET_ALL_BENEFICIARIES } from '~/store/actionTypes';
// import { store } from '~/store/store';

let currentSelected = {};

export class ShowFamilyMemberList extends Component {
	static navigationOptions = ({ navigation }) => {
		const { getParam } = navigation;
		return {
			title: 'Family Members',
			headerTransparent: false,
			hideBackButton: false,
			leftButtons: [],
			rightButtons: [{
				onPress: () => { getParam('onAddNewEntry')(); },
				icon: 'plus',
			}],
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		// users: PropTypes.object.isRequired,
		familyMembers: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props);

		this.state = {
			safeAreaInsets: {
				top: 0, left: 0, bottom: 0, right: 0,
			},
			// provinceFilter: '',
			options: props.familyMembers,
			// txtInput: '',
			onUpdateHousehold: this.props.navigation.getParam('onUpdateHousehold', () => {}),
			selected: {},
			// isEditting: false,
		};

		this.debounceOnPressBack = _.debounce(this.onPressBack, 3000, {
			leading: true,
			trailing: false,
		});
		this.didFocusSubscription = props.navigation.addListener('didFocus', () =>
			BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid));
		this.willBlurSubscription = this.props.navigation.addListener('willBlur', () =>
			BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid));
		this.props.navigation.setParams({
			onPressBack: this.debounceOnPressBack,
		});
		// store.dispatch({ type: RESET_ALL_BENEFICIARIES });
		this.props.navigation.setParams({
			onAddNewEntry: this.onAddNewEntry,
		});
	}

	componentWillUnmount() {
		if (!_.isEmpty(this.didFocusSubscription)) this.didFocusSubscription.remove();
		if (!_.isEmpty(this.willBlurSubscription)) this.willBlurSubscription.remove();
	}

	static getDerivedStateFromProps(nextProps, prevState) {
		if (!_.isEqual(prevState.options, nextProps.familyMembers)) {
			return { options: nextProps.familyMembers };
		}
		return null;
	}

	onAddNewEntry = () => {
		const memberRefId = this.props.navigation.getParam('memberRefId', '');
		console.log('ADD MEMBER: ', memberRefId);
		this.props.navigation.push('AddFamilyMember', { memberRefId });

	}

	onBackButtonPressAndroid = () => {
		this.debounceOnPressBack();
		return true;
	};

	onPressBack = (selected) => {
		if (!_.isEmpty(selected)) {
			this.state.onUpdateHousehold(selected);
		}
		this.props.navigation.goBack();
	}

	getSafeMargin() {
		return {
			marginBottom: this.state.safeAreaInsets.bottom,
			marginLeft: this.state.safeAreaInsets.left,
			marginRight: this.state.safeAreaInsets.right,
		};
	}

	selectItem = (item = {}) => {
		if (!_.isEmpty(item)) {
			currentSelected = item;
			// this.setState({ selected: item });
			this.contentActionSheet.open();
			// console.log('item: ', item.lastName);
		}
	}

	editInfo = () => {
		if (!_.isEmpty(currentSelected)) {
			const payload = { selected: currentSelected.memberId };
			payload[`${currentSelected.memberId}`] = currentSelected;
			this.props.navigation.push('EditFamilyMember', payload);
		}
		// this.setState({ isEditting: true });
		this.contentActionSheet.close();
	}

	showQR = () => {
		this.props.navigation.push('ShowQRCode', { data: this.state.selected });
		this.contentActionSheet.close();
	}

	renderEmptyMember = () => (
		<View style={[styles.container, { justifyContent: 'center', marginTop: -100 }]}>
			<ContentGridEmpty>
				<ContentGridEmpty.Title>Household Members</ContentGridEmpty.Title>
				<ContentGridEmpty.Description>Add beneficiary household member</ContentGridEmpty.Description>
			</ContentGridEmpty>
		</View>
	);

	render() {
		const { options } = this.state;
		return (
			<View style={[styles.container, this.getSafeMargin()]}>
				{ (!_.isEmpty(options)) ?
					<FlatList
						ref={(ref) => { this.flatListRef = ref; }}
						style={styles.listContainer}
						data={options}
						keyExtractor={({ lastName, firstName, middleName }) => `${lastName}${firstName}${middleName}`}
						inverted={false}
						renderItem={({ item, index }) => {
							// const { lastName, firstName, middleName, familyPosition, age, dob, } = item;
							const firstName = _.get(item, 'firstName', '');
							const lastName = _.get(item, 'lastName', '');
							const middleName = _.get(item, 'middleName', '');
							const dob = _.get(item, 'dob', '');
							const sex = _.get(item, 'sex', '');
							const avatarPhoto = _.get(item, 'avatarPhoto', '');
							const age = _.get(item, 'age', '');
							const familyPosition = _.get(item, 'familyPosition', '');
							let suffix = _.get(item, 'suffix', '');
							suffix = !_.isEqual(suffix, 'None') ? suffix : '';
							const labelTxt = `Name: ${lastName}, ${firstName} ${middleName} ${suffix} - Age: ${age}, DoB: ${dob} Gender: ${sex}, Position: ${familyPosition}`;
							// const randColor = `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
							return (
								<TouchableOpacity
									style={[
										styles.option,
										index === options.length - 1 && styles.lastOption,
									]}
									key={item}
									onPress={() => { this.selectItem(item); }}
									disabled={_.isEqual(item, i18n.t('common.noResult'))}
								>
									<View style={[styles.avatarContainer]}>
										<Avatar
											firstName={_.isEmpty(firstName) ? 'M' : firstName}
											lastName={_.isEmpty(lastName) ? 'E' : lastName}
											size="default"
											source={(!_.isEmpty(avatarPhoto) ? { uri: avatarPhoto } : null)}
											style={{ backgroundColor: basicColor.wrikeBg }}
										/>
									</View>
									<View style={styles.optionLabel}>
										<Text
											textStyle="subhead"
											color={basicColor.wrikeBg}
											numberOfLines={3}
										>{labelTxt}
										</Text>
									</View>
								</TouchableOpacity>
							);
						}}
					/> : this.renderEmptyMember()
				}
				<ActionSheet
					ref={(actionSheet) => { this.contentActionSheet = actionSheet; }}
				>
					<ActionSheet.Action onPress={this.showInfo} testID="View">View</ActionSheet.Action>
					<ActionSheet.Action onPress={this.editInfo} testID="EditInfo">Edit Information</ActionSheet.Action>
					<ActionSheet.Cancel testID="Cancel">{i18n.t('common.cancel')}</ActionSheet.Cancel>
				</ActionSheet>
			</View>
		);
	}
}

const mapStateToProps = (state, props) => {
	const memberRefId = props.navigation.getParam('memberRefId', '');
	const familyMembers =
		(_.has(state.beneficiaries.manualBeneMemberSave, memberRefId)) ?
			state.beneficiaries.manualBeneMemberSave[memberRefId] : [];
	// console.log('FAMILY MEMBERS: ', familyMembers);
	return {
		isConnected: state.network.isConnected,
		users: state.users,
		familyMembers,
	};
};

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