import _ from 'lodash';
import React, { Component } from 'react';
import {
	View,
	FlatList,
	TouchableOpacity,
	BackHandler,
	Alert,
} from 'react-native';
import { connect } from 'react-redux';
import {
	Text,
	ActionSheet,
	Avatar,
} 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';

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		// users: PropTypes.object.isRequired,
		beneficiaries: PropTypes.object.isRequired,
		members: PropTypes.array.isRequired,
	}

	constructor(props) {
		super(props);

		// console.log('LIST: ', props.beneficiaries);

		this.state = {
			safeAreaInsets: {
				top: 0, left: 0, bottom: 0, right: 0,
			},
			options: _.uniqBy(props.beneficiaries, 'memberRefId'),
			onUpdateHousehold: this.props.navigation.getParam('onUpdateHousehold', () => {}),
			selected: {},
		};
		// console.log('LIST: ', this.state.options);
		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,
		});
		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) {
		const { manualBeneSave } = nextProps.beneficiaries;
		if (!_.isEqual(prevState.options, manualBeneSave)) {
			return { options: _.uniqBy(manualBeneSave, 'memberRefId') };
		}
		return null;
	}

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

	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)) {
			this.setState({ selected: item });
			this.contentActionSheet.open();
			// console.log('item: ', item.lastName);
		}
	}

	editInfo = () => {
		this.props.navigation.push('EditBeneficiaryRecord', { selected: this.state.selected });
		this.contentActionSheet.close();
	}

	showPhotos = () => {
		const { memberRefId } = this.state.selected;
		this.props.navigation.push('PhotoList', { memberRefId });
		this.contentActionSheet.close();
	}

	showInfo = () => {
		// console.log('EDITitem: ', this.state.selected.lastName);
		const {
			firstName,
			lastName,
			middleName,
			age,
			dob,
			programID,
			remarks,
			region,
			province,
			municipality,
			barangay,
			cRegion,
			cProvince,
			cMunicipality,
			cBarangay,
			sex,
			occupation,
			sector,
			monthlyIncome,
			education,
			houseOwnership,
			healthCondition,
			program,
			reliefAssistance,
			dateCreated,
			beneficiaryMobile,
			emailAddress,
		} = this.state.selected;
		Alert.alert(
			'MAAGApp - Basic Info',
			`Date Created: ${new Date(dateCreated * 1000)}
			\nName: ${firstName} ${middleName} ${lastName}
			\nAge: ${age}, DoB: ${dob}, Sex: ${sex}
			\nMobile: ${beneficiaryMobile} Email: ${emailAddress}
			\nEducation: ${education} Occupation: ${occupation} Sector: ${sector} Income: ${monthlyIncome}
			\nHouse: ${houseOwnership} Health: ${healthCondition}
			\nCurrent Address:  ${cRegion.regDesc}, ${cProvince.provDesc}, ${cMunicipality.citymunDesc}, ${cBarangay.brgyDesc}
			\nBirth Place:  ${region.regDesc}, ${province.provDesc}, ${municipality.citymunDesc}, ${barangay.brgyDesc}
			\nProgram:  ${program} - ${programID}
			\nRelief Assistance: ${reliefAssistance}
			\nRemarks: ${remarks}`,
			[
				{
					text: i18n.t('common.ok'),
					onPress: () => { this.contentActionSheet.close(); },
				},
			],
			{ cancelable: false },
		);
	}

	showMember = () => {
		if (!_.isEmpty(this.state.selected)) {
			const { memberRefId, lastName, firstName } = this.state.selected;
			// console.log('DATA: ',data);

			if (!_.isEmpty(this.props.members)) {
				this.props.navigation.push('ShowFamilyMemberList', { memberRefId });
				this.contentActionSheet.close();
			} else {
				this.showAlert(
					'MAAGApp - Reminder',
					`Member ${lastName}, ${firstName} does not have family member yet. Do you wish to add member now?`,
					() => { console.log('CONTINUE'); },
					() => { this.props.navigation.push('AddFamilyMember', { memberRefId }); },
				);
			}
		}
	}

	addMember = () => {
		if (!_.isEmpty(this.state.selected)) {
			const { memberRefId } = this.state.selected;
			console.log('ADD MEMBER: ', memberRefId);
			this.props.navigation.push('AddFamilyMember', { data: this.state.selected, memberRefId });
		}
		this.contentActionSheet.close();
	}

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

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

	render() {
		return (
			<View style={[styles.container, this.getSafeMargin()]}>
				<FlatList
					ref={(ref) => { this.flatListRef = ref; }}
					style={styles.listContainer}
					data={this.props.beneficiaries}
					keyExtractor={(item) => (_.isEmpty(item) ? 0 : item.dateCreated)}
					inverted={false}
					renderItem={({ 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 reliefAssistance = _.get(item, 'reliefAssistance', '');
						const avatarPhoto = _.get(item, 'avatarPhoto', '');
						const program = _.get(item, 'program', '');
						const age = _.get(item, 'age', '');
						let suffix = _.get(item, 'suffix', '');
						suffix = !_.isEqual(suffix, 'None') ? suffix : '';
						const labelTxt =
							`Name: ${lastName}, ${firstName} ${middleName} ${suffix} - Age: ${age}, DoB: ${dob} Gender: ${sex}, ${reliefAssistance}, ${program}`;
						return (
							<TouchableOpacity
								style={[
									styles.option,
								]}
								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)}
									/>
								</View>
								<View style={[
									styles.optionLabel,
								]}
								>
									<Text
										textStyle="subhead"
										color={basicColor.wrikeBg}
										numberOfLines={10}
									>{labelTxt}
									</Text>
								</View>
							</TouchableOpacity>
						);
					}}
				/>
				<ActionSheet
					ref={(actionSheet) => { this.contentActionSheet = actionSheet; }}
				>
					<ActionSheet.Action onPress={this.showInfo} testID="View">View</ActionSheet.Action>
					<ActionSheet.Action onPress={this.showPhotos} testID="Photos">Photos</ActionSheet.Action>
					<ActionSheet.Action onPress={this.editInfo} testID="EditInfo">Edit Information</ActionSheet.Action>
					<ActionSheet.Action onPress={this.showMember} testID="ShowFamMember">Show Family Member</ActionSheet.Action>
					<ActionSheet.Action onPress={this.addMember} testID="AddFamMember">Add Family Member</ActionSheet.Action>
					<ActionSheet.Action onPress={this.showQR} testID="ShowQR">Show QRCode</ActionSheet.Action>
					{/* <ActionSheet.Action onPress={() => {}} color="red" testID="Delete">Delete</ActionSheet.Action> */}
					<ActionSheet.Cancel testID="Cancel">{i18n.t('common.cancel')}</ActionSheet.Cancel>
				</ActionSheet>
			</View>
		);
	}
}

const mapStateToProps = (state) => ({
	isConnected: state.network.isConnected,
	users: state.users,
	beneficiaries: _.filter(state.beneficiaries.manualBeneSave, (o) => !_.isEmpty(o)),
	members: _.filter(state.beneficiaries.manualBeneMemberSave, (o) => !_.isEmpty(o)),
});

export default connect(mapStateToProps)(BeneficiaryList);
