import React, { Component } from 'react';
import _ from 'lodash';
import { FlatList, RefreshControl, View, Platform, StyleSheet, PixelRatio } from 'react-native';
import { Loading, color, ContentGridEmpty } from 'nixplay-ui-kit';
import { checkInternetConnection } from 'react-native-offline';

import PropTypes from 'prop-types';
import i18n from '~/locale/i18n';
import { ActivityListItem } from '~/components/FriendActivities/listItem';

const styles = StyleSheet.create({
	loadingContainer: {
		backgroundColor: color.white,
		flex: 1,
		position: 'absolute',
		width: '100%',
		height: '100%',
		justifyContent: 'center',
	},
	baseContainer: {
		opacity: 1,
	},
});

const isAndroid = Platform.OS !== 'ios';
const numItemRender = (PixelRatio.get() === 1) ? 10 : 19;

export class TimestampedList extends Component {
	static propTypes = {
		data: PropTypes.array.isRequired,
		getData: PropTypes.func.isRequired,
		loading: PropTypes.bool.isRequired,
		firstName: PropTypes.string.isRequired,
		lastName: PropTypes.string.isRequired,
		onMediaItemPress: PropTypes.func.isRequired,
		onEndReached: PropTypes.func.isRequired,
		numPerPage: PropTypes.number,
		uuid: PropTypes.string.isRequired,
		source: PropTypes.any,
		languageCode: PropTypes.string,
	}

	static defaultProps = {
		numPerPage: 20,
		source: null,
		languageCode: '',
	}

	constructor(props) {
		super(props);

		this.state = {
			refreshing: false,
			didScroll: false,
			isVisibleLoading: true,
			loading: false,
		};

		this.debouncerScroll = _.debounce(() => {
			if (!this.state.didScroll && !_.isEmpty(this.flatList)) {
				this.flatList.scrollToEnd({ animated: false });
			}
		}, 400, { leading: false, trailing: true });
		this.refreshData = this.refreshData.bind(this);
		this.onEndReached = this.onEndReached.bind(this);
	}

	static getDerivedStateFromProps(nextProps, prevState) {
		if ((nextProps.loading !== prevState.loading)) {
			return { loading: nextProps.loading, isVisibleLoading: false };
		}
		return null;
	}

	componentWillUnmount() {
		if (this.debouncerScroll) {
			this.debouncerScroll.cancel();
		}
	}

	onEndReached() {
		if (this.state.isVisibleLoading) {
			this.setState({ isVisibleLoading: false });
		}
	}

	onProcessAvatar = (avatar) => {
		if (_.has(avatar, 'uri')) {
			this.props.onEndReached(avatar);
		}
	}

	refreshData = () => {
		if (this.debouncerScroll) {
			this.debouncerScroll.cancel();
		}
		checkInternetConnection().then(isConnected => {
			if (isConnected) {
				if (this.state.refreshing) return;
				if (!this.props.loading && !_.isEmpty(this)) {
					this.setState({
						refreshing: true,
						didScroll: true,
					}, () => {
						this.props.getData(
							true,
							() => { // resolve
								this.setState({ refreshing: false });
							},
							() => { // reject
								this.setState({ refreshing: false });
							},
						);
					});
				}
			}
		});
	}

	renderFooter = () => (<View style={{ marginBottom: 30 }} />);

	renderLoading = (opacity) => (
		<View
			style={[styles.loadingContainer, { opacity }]}
			pointerEvents={(opacity) ? 'auto' : 'none'}
		>
			<Loading
				indeterminate
				withText
				text={i18n.t('friends.LoadingActivities')}
			/>
		</View>
	);

	renderEmptyPhotos = () => (
		<View style={styles.container}>
			<ContentGridEmpty>
				<ContentGridEmpty.Icon name="photos" />
				<ContentGridEmpty.Title>Beneficiary Photos</ContentGridEmpty.Title>
				<ContentGridEmpty.Description>Add required photos</ContentGridEmpty.Description>
			</ContentGridEmpty>
		</View>
	);

	render() {
		const opacity = (this.state.isVisibleLoading) ? 1 : 0;
		return (
			<View style={{ flex: 1 }}>
				{ (!_.isEmpty(this.props.photos) ? (
					<FlatList
						{...this.props}
						ref={(comp) => { this.flatList = comp; }}
						data={this.props.data}
						contentContainerStyle={styles.baseContainer}
						showsVerticalScrollIndicator={false}
						removeClippedSubviews={isAndroid}
						initialNumToRender={numItemRender}
						maxToRenderPerBatch={numItemRender}
						onContentSizeChange={() => {
							this.debouncerScroll();
						}}
						onEndReached={this.onEndReached}
						renderItem={({ item }) => {
							this.onProcessAvatar(this.props.source);
							return (
								<ActivityListItem
									uuid={this.props.uuid}
									activity={item}
									firstName={this.props.firstName}
									lastName={this.props.lastName}
									onMediaItemPress={this.props.onMediaItemPress}
									source={this.props.source}
									languageCode={this.props.languageCode}
								/>
							);
						}}
						refreshControl={
							<RefreshControl
								refreshing={this.props.loading}
								onRefresh={() => { this.refreshData(); }}
								title=""
							/>
						}
						ListFooterComponent={this.renderFooter}
					/>
					) : (this.renderEmptyPhotos())
				}
				{this.renderLoading(opacity)}
			</View>
		);
	}
}
