import _ from 'lodash';
import React, { Component } from 'react';
import {
	View,
	FlatList,
	TouchableOpacity,
	BackHandler,
	Alert,
	Image,
	PixelRatio,
} from 'react-native';
import ImageResizer from 'react-native-image-resizer';
import { connect } from 'react-redux';
import {
	Text,
	ActionSheet,
	ContentGridEmpty,
} from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import { ADD_PHOTO_BENEFICIARY, GET_ASSETS, GET_PHOTO_BENEFICIARY } from '~/store/actionTypes';
import { PickerOptions } from '~/components/Photos/pickerOptions';
import i18n from '~/locale/i18n';
import { color as basicColor } from '~/styles/variables';
import { styles } from './styles';

let currentState = {};

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

	static propTypes = {
		navigation: PropTypes.object.isRequired,
		photos: PropTypes.object.isRequired,
		launchImagePicker: PropTypes.func.isRequired,
		addBeneficiaryPhoto: PropTypes.func.isRequired,
	}

	constructor(props) {
		super(props);

		const memberRefId = this.props.navigation.getParam('memberRefId', '');
		currentState = { ...currentState, memberRefId };
		console.log('PHOTOS: ', memberRefId);
		this.state = {
			safeAreaInsets: {
				top: 0, left: 0, bottom: 0, right: 0,
			},
			options: [],
			selected: {},
			memberRefId,
		};
		// 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) {
	// 	if (!_.isEqual(prevState.options, nextProps.photos)) {
	// 		const uniqBy = _.uniqBy(nextProps.photos, 'memberRefId');
	// 		const filtered = _.filter(uniqBy, (o) => (!_.isEmpty(o) && _.isEqual(o.memberRefId, currentState.memberRefId)));
	// 		return { options: filtered };
	// 	}
	// 	return null;
	// }

	onAddNewEntry = () => {
		// launch photo library
		this.launchImagePicker();
	}

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

	deletePhoto = () => {
		if (!_.isEmpty(this.state.selected)) {
			console.log('DELETE');
		}
	}

	showPhoto = () => {
		if (!_.isEmpty(this.state.selected)) {
			console.log('SHOW');
		}
	}

	addPhoto = () => {
		if (!_.isEmpty(this.state.selected)) {
			console.log('ADD');
		}
	}

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

	processSourceImage = (rawImage) => {
		this.setState({ }, async () => {
			try {
				const { memberRefId } = this.state;
				let sourceUri = rawImage;
				Image.getSize(sourceUri, async (w, h) => {
					const safeSize = PixelRatio.roundToNearestPixel(1000); // approximate preferred max dimension size
					let width = w;
					let height = h;

					if (width > safeSize && width > height) {
						const percentageDiff = (safeSize / width);
						width = safeSize;
						height = PixelRatio.roundToNearestPixel(height * percentageDiff);
					} else if (height > safeSize && height > width) {
						const percentageDiff = (safeSize / height);
						height = safeSize;
						width = PixelRatio.roundToNearestPixel(width * percentageDiff);
					}
					const resizedImage = await ImageResizer.createResizedImage(sourceUri, width, height, 'JPEG', 100, 0, null);
					sourceUri = resizedImage.uri;
					// save to reducer
					// console.log(`SOURCE: ${sourceUri} BENE: ${memberRefId}`);
					const dateCreated = Math.floor(new Date().getTime() / 1000.0);
					this.props.addBeneficiaryPhoto({ sourceUri, memberRefId, dateCreated });
				}, (e) => {
					console.log('error2: ', e);
				});
			} catch (e) {
				console.log('error1: ', e);
			}
		});
	};

	launchImagePicker = () => {
		this.props.launchImagePicker({
			options: {
				...PickerOptions([]),
				maximumImageCount: 1,
				imageSelectionLimit: i18n.t('contents.imageSelectionLimit', { count: 1 }),
				mediaType: 'image',
				allowsMultipleSelection: '0',
			},
			resolve: (imagesPicked) => {
				if (imagesPicked && imagesPicked[0] && imagesPicked[0].uri) {
					console.log('IMAGE: ', imagesPicked[0].uri);
					this.processSourceImage(imagesPicked[0].uri);
				}
			},
		});
	}

	renderPhotoItem = (item) => (
		<TouchableOpacity
			style={[
				styles.option,
			]}
			key={item.dateCreated}
			onPress={() => { }}
			disabled={_.isEqual(item, i18n.t('common.noResult'))}
		>
			<View style={[styles.avatarContainer]}>
				<Image source={{ uri: item.sourceUri }} style={styles.thumb} resizeMode="contain" />
			</View>
			<View style={[
				styles.optionLabel,
				{ marginTop: 6 },
			]}
			>
				<Text
					textStyle="subhead"
					color={basicColor.wrikeBg}
					numberOfLines={10}
				>{`Created: ${(new Date(item.dateCreated * 1000))}, ID: ${item.dateCreated}`}
				</Text>
			</View>
		</TouchableOpacity>
	)

	renderEmptyPhotos = () => (
		<View style={[styles.container, { justifyContent: 'center', marginTop: -100 }]}>
			<ContentGridEmpty>
				<ContentGridEmpty.Title>Beneficiary Photos</ContentGridEmpty.Title>
				<ContentGridEmpty.Description>Add required photos</ContentGridEmpty.Description>
			</ContentGridEmpty>
		</View>
	);

	render() {
		return (
			<View style={[styles.container, this.getSafeMargin()]}>
				{ (!_.isEmpty(this.props.photos)) ?
					<FlatList
						ref={(ref) => { this.flatListRef = ref; }}
						style={styles.listContainer}
						data={this.props.photos}
						keyExtractor={(item) => (_.isEmpty(item) ? 0 : item.dateCreated)}
						inverted={false}
						renderItem={({ item }) => this.renderPhotoItem(item)}
					/> : this.renderEmptyPhotos()
				}
				<ActionSheet
					ref={(actionSheet) => { this.contentActionSheet = actionSheet; }}
				>
					<ActionSheet.Action onPress={() => {}} testID="showPhoto"></ActionSheet.Action>
					<ActionSheet.Action onPress={this.addPhoto} testID="addPhoto">Add Photo</ActionSheet.Action>
					<ActionSheet.Action onPress={this.deletePhoto} testID="deletePhoto">Delete Photo</ActionSheet.Action>
					<ActionSheet.Cancel testID="Cancel">{i18n.t('common.cancel')}</ActionSheet.Cancel>
				</ActionSheet>
			</View>
		);
	}
}

const mapStateToProps = (state, props) => {
	const memberRefId = props.navigation.getParam('memberRefId', '');
	return {
		isConnected: state.network.isConnected,
		users: state.users,
		photos: state.photos.beneficiaryPhotos[memberRefId],
	};
};

export const mapActionsToProps = (dispatch) => ({
	launchImagePicker(payload) {
		dispatch({ type: GET_ASSETS, payload });
	},
	addBeneficiaryPhoto(payload) {
		dispatch({ type: ADD_PHOTO_BENEFICIARY, payload });
	},
});

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