import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { ContentGridEmpty, Button } from 'nixplay-ui-kit';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { checkInternetConnection, offlineActionTypes } from 'react-native-offline';
import i18n from '~/locale/i18n';
import { SHOW_TOAST_ERROR } from '~/store/actionTypes';

const styles = StyleSheet.create({
	container: {
		marginHorizontal: 20,
		flex: 1,
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingBottom: 64,
	},
});

class OfflineEmpty extends Component {
	static propTypes = {
		onPress: PropTypes.func,
		title: PropTypes.string,
		description: PropTypes.string,
		onConnectionChanged: PropTypes.func.isRequired,
		toastError: PropTypes.func.isRequired,
	};

	static defaultProps = {
		onPress: null,
		title: i18n.t('common.noNetwork'),
		description: i18n.t('common.offlineRetryAgainDescription', { contentsType: i18n.t('common.contents') }),
	};

	componentWillMount() {
		this.debounceCheckInternetConnection = _.debounce(this.checkConnection, 1000);
	}

	componentWillUnmount() {
		this.debounceCheckInternetConnection.cancel();
	}

	/**
	 * James Kong 20190128
	 * I want to actively check the connectivity, debounce to avoid overload
	 */
	checkConnection = () => checkInternetConnection()
		.then(isConnected => {
			if (isConnected) {
				this.props.onConnectionChanged(isConnected);
				this.props.onPress();
			} else {
				this.props.toastError({ text: i18n.t('common.noInternetConnection') });
			}
		});

	render() {
		return (
			<View style={styles.container}>
				<ContentGridEmpty>
					<ContentGridEmpty.Icon name="cloud-offline" />
					<ContentGridEmpty.Title>
						{this.props.title}
					</ContentGridEmpty.Title>
					<ContentGridEmpty.Description>
						{this.props.description}
					</ContentGridEmpty.Description>
					<ContentGridEmpty.Additional>
						{typeof this.props.onPress === 'function' &&
							<Button
								testID="Refresh"
								style={styles.button}
								type="primary"
								shadow="long"
								onPress={this.debounceCheckInternetConnection}
							>
								<Button.Icon name="refresh" />
								<Button.Text>{i18n.t('common.tapToRetry')}</Button.Text>
							</Button>
						}
					</ContentGridEmpty.Additional>
				</ContentGridEmpty>
			</View>
		);
	}
}

const mapActionsToProps = (dispatch) => ({
	onConnectionChanged(isConnected) {
		dispatch({
			type: offlineActionTypes.CONNECTION_CHANGE,
			payload: isConnected,
		});
	},
	toastError(payload) {
		dispatch({ type: SHOW_TOAST_ERROR, payload });
	},
});

export default connect(null, mapActionsToProps)(OfflineEmpty);
