import React, { Component } from 'react';
import _ from 'lodash';
import {
	View,
	FlatList,
	TouchableOpacity,
	BackHandler,
} from 'react-native';
import { connect } from 'react-redux';
import {
	Text,
	NixplayIcon as Icon,
} from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import i18n from '~/locale/i18n';
import lifeStatus from '~/store/lifeStatusOpts.json';
import { color as basicColor } from '~/styles/variables';
import { styles } from './styles';

export class ReliefMultiSelection extends Component {
	static navigationOptions = ({ navigation }) => {
		const { getParam } = navigation;
		return {
			title: 'Select Relief Assistance',
			headerTransparent: false,
			hideBackButton: true,
			leftButtons: [{
				icon: 'close',
				onPress: () => { getParam('onPressBack')(); },
			}],
			rightButtons: [{
				icon: 'check',
				onPress: () => { getParam('onPressDone')(); },
			}],
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props);

		// provinces
		const { receiveAssitance } = lifeStatus;
		const selectedAssitance = this.props.navigation.getParam('selected', 'SAP - Emergency Subsidy Program,Disaster - Family Food Pack,Disaster - Emergency Shelter Assistance');

		this.state = {
			safeAreaInsets: {
				top: 0, left: 0, bottom: 0, right: 0,
			},
			options: receiveAssitance,
			relief: (!_.isEmpty(selectedAssitance)) ? selectedAssitance.split(',') : [],
			onUpdate: this.props.navigation.getParam('onUpdate', () => {}),
		};

		this.debounceOnPressBack = _.debounce(this.onPressBack, 3000, {
			leading: true,
			trailing: false,
		});
		this.debounceonPressDone = _.debounce(this.onPressDone, 1000, {
			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,
			onPressDone: this.debounceonPressDone,
		});
	}

	componentWillUnmount() {
		if (!_.isEmpty(this.didFocusSubscription)) this.didFocusSubscription.remove();
		if (!_.isEmpty(this.willBlurSubscription)) this.willBlurSubscription.remove();
	}

	onBackButtonPressAndroid = () => {
		this.debounceOnPressBack();
		return true;
	};

	onPressBack = () => {
		if (!_.isEmpty(this.state.relief)) {
			this.state.onUpdate(this.state.relief);
		}
		this.props.navigation.goBack();
	}

	onPressDone = () => {
		this.state.onUpdate(this.state.relief);
		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)) {
			const { relief } = this.state;
			if (!_.isEmpty(relief) && (!(relief.indexOf(item) === -1))) {
				// delete
				const newRelief = _.remove(relief, (o) => (o !== item));
				console.log('DELETE: ', newRelief);
				this.setState({ relief: newRelief });
			} else {
				// add
				console.log('ADD');
				const newRelief = _.flatten([...item, relief]);
				this.setState({ relief: newRelief });
			}
		}
	}

	render() {
		const { options, relief } = this.state;
		console.log('relief: ', relief);
		return (
			<View style={[styles.container, this.getSafeMargin()]}>
				<FlatList
					ref={(ref) => { this.flatListRef = ref; }}
					style={styles.listContainer}
					data={options}
					keyExtractor={(item) => item}
					inverted={false}
					renderItem={({ item, index }) => {
						const isSelected = (!(relief.indexOf(item) === -1));
						return (
							<TouchableOpacity
								style={[
									styles.option,
									index === options.length - 1 && styles.lastOption,
								]}
								key={item}
								onPress={() => { this.selectItem(item); }}
								disabled={_.isEqual(item, i18n.t('common.noResult'))}
							>
								<View style={[
									styles.optionLabel,
								]}
								>
									<Text
										textStyle="subhead"
										color={isSelected ? basicColor.wrikeGreen2 : basicColor.wrikeBg}
										numberOfLines={2}
									>{item}
									</Text>
								</View>
								{isSelected && <Icon name="check-thick-small" testID="Check" color={basicColor.wrikeGreen2} size={15} />}
							</TouchableOpacity>
						);
					}}
				/>
			</View>
		);
	}
}

export default connect(null, null)(ReliefMultiSelection);
