import React, { PureComponent } from 'react';
import { View, StyleSheet, Platform, ActivityIndicator } from 'react-native';
import DraggableFlatList from 'react-native-draggable-flatlist';
import { Text } from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import { checkInternetConnection } from 'react-native-offline';
import i18n from '~/locale/i18n';

const styles = StyleSheet.create({
	loadingContainer: {
		alignItems: 'center',
		justifyContent: 'center',
	},
	flatListFix: {
		borderWidth: 1,
		borderColor: 'transparent',
	},
});

const isAndroid = Platform.OS !== 'ios';

export class InfiniteScroll extends PureComponent {
	static propTypes = {
		data: PropTypes.array.isRequired,
		getData: PropTypes.func.isRequired,
		loading: PropTypes.bool.isRequired,
		hasMore: PropTypes.bool,
		numPerPage: PropTypes.number,
		flatListRef: PropTypes.func,
		style: PropTypes.any,
	}

	static defaultProps = {
		hasMore: true,
		numPerPage: 30,
		flatListRef: () => {},
		style: null,
	}

	constructor(props) {
		super(props);

		this.state = {
			offset: 0,
			refreshing: false,
		};
	}

	componentDidMount() {
		this.requestData();
	}

	componentWillReceiveProps(nextProps) {
		if ((this.props.loading && !nextProps.loading)) {
			this.setState({ refreshing: false });
		}
	}

	requestData = () => {
		this.props.getData(
			this.state.offset, // start index (offset)
			this.props.numPerPage, // number per page
		);
	}

	refreshData = () => {
		checkInternetConnection().then(isConnected => {
			if (isConnected) {
				if (this.state.refreshing) return;
				this.setState({
					offset: 0,
					refreshing: true,
				}, () => {
					this.requestData();
				});
			} else {
				this.setState({ refreshing: false });
			}
		});
	}

	loadMoreData = () => {
		if (!this.props.hasMore) return;
		this.setState({
			offset: this.props.data.length,
		}, () => {
			this.requestData();
		});
	}

	render() {
		return (
			<DraggableFlatList
				{...this.props}
				ref={this.props.flatListRef}
				data={this.props.data}
				extraData={this.props.data}
				refreshing={this.state.refreshing}
				onRefresh={this.refreshData}
				onEndReached={this.loadMoreData}
				onEndReachedThreshold={0.5}
				initialNumToRender={50}
				maxToRenderPerBatch={50}
				scrollEventThrottle={16}
				scrollPercent={10}
				ListFooterComponent={() => (
					this.props.loading && this.state.offset > 0 && this.props.hasMore ? (
						<View style={styles.loadingContainer}>
							<ActivityIndicator style={{ marginVertical: 5 }} />
							<Text textStyle="caption2">{i18n.t('common.loading')}</Text>
						</View>
					) : (
						<View />
					)
				)}
				// Weird fix for the onReachEnd Sometimes doesn't work on android devices.
				style={[(isAndroid && styles.flatListFix)]}
			/>
		);
	}
}
