import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import PropTypes from 'prop-types';
import { RecyclerListView, DataProvider, LayoutProvider } from 'recyclerlistview';
import _ from 'lodash';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

export class ViewPager extends Component {
	static propTypes = {
		data: PropTypes.array.isRequired,
		onPageSelected: PropTypes.func,
		initialRenderIndex: PropTypes.number,
		layoutProvider: PropTypes.object,
	};

	static defaultProps = {
		onPageSelected: () => { },
		initialRenderIndex: 0,
		layoutProvider: new LayoutProvider(
			() => 0,
			// eslint-disable-next-line no-param-reassign
			(type, dim) => { dim.width = screenWidth; dim.height = screenHeight; },
		),
	};

	constructor(props) {
		super(props);

		this.state = {
			index: props.initialRenderIndex,
			dataProvider: new DataProvider((r1, r2) => !_.isEqual(r1, r2)).cloneWithRows(props.data),
		};
	}

	componentDidMount() {
	}

	componentWillReceiveProps(nextProps) {
		if (!_.isEqual(nextProps.data, this.props.data) && !_.isEmpty(nextProps.data)) {
			let nextIndex = this.state.index;
			if (nextProps.data.length < this.props.data.length && nextIndex >= nextProps.data.length) {
				nextIndex = nextProps.data.length - 1;
			}
			this.recyclerListView.scrollToIndex(nextIndex);
			setTimeout(() => {
				this.setState({
					index: nextIndex,
					dataProvider: this.state.dataProvider.cloneWithRows(nextProps.data),
				});
				this.props.onPageSelected(nextIndex);
			}, 100);
		}
	}

	momentumScrollEnd = (event) => {
		const index = _.round(event.nativeEvent.contentOffset.x / screenWidth);
		this.setState({ index });
		this.props.onPageSelected(index);
	}

	scrollToIndex = (index) => {
		const prevIndex = this.state.index;
		this.setState({ index }, () => {
			this.recyclerListView.scrollToIndex(index, Math.abs(index - prevIndex) < 2);
			this.props.onPageSelected(index);
		});
	}

	render() {
		return (
			<RecyclerListView
				{...this.props}
				ref={(ref) => { this.recyclerListView = ref; }}
				scrollEventThrottle={160}
				pagingEnabled
				isHorizontal
				layoutProvider={this.props.layoutProvider}
				dataProvider={this.state.dataProvider}
				onMomentumScrollEnd={this.momentumScrollEnd}
				removeClippedSubviews
			/>
		);
	}
}
