import React, { Component } from 'react';
import _ from 'lodash';
import {
	View,
	FlatList,
	TouchableOpacity,
	BackHandler,
	Platform,
} from 'react-native';
import { reduxForm } from 'redux-form';
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 barangayList from '~/store/barangay.json';
import { TextInput } from '~comp/reduxForm';
import { color as basicColor } from '~/styles/variables';
import { styles } from './styles';

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

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

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

	constructor(props) {
		super(props);
		const citymunCode = this.props.navigation.getParam('citymunCode', ''); // province code
		const { RECORDS: Barangay } = barangayList; // municipality
		const filterBarangay = _.filter(Barangay, ['citymunCode', citymunCode]);

		this.state = {
			safeAreaInsets: {
				top: 0, left: 0, bottom: 0, right: 0,
			},
			options: _.sortBy(filterBarangay, ['brgyDesc']),
			// citymunCode,
			// txtInput: '',
			onUpdateBarangay: this.props.navigation.getParam('onUpdateBarangay', () => {}),
			barangay: this.props.navigation.getParam('selected', ''),
			locationFilter: '',
			fieldHasValue: false,
		};

		this.debounceOnPressBack = _.debounce(this.onPressBack, 3000, {
			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,
		});
	}

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

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

	onPressBack = (selected) => {
		if (!_.isEmpty(selected)) {
			this.state.onUpdateBarangay(selected);
		}
		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)) {
			this.debounceOnPressBack(item);
		}
	}

	checkCrossButton = (key) => {
		if (!_.isEmpty(key)) {
			this.setState({ fieldHasValue: true });
		} else {
			this.setState({ fieldHasValue: false });
		}
	}

	updateList = (key = '') => {
		const citymunCode = this.props.navigation.getParam('citymunCode', ''); // province code
		const { RECORDS: Barangay } = barangayList; // municipality
		const filterBarangay = _.filter(Barangay, ['citymunCode', citymunCode]);

		this.checkCrossButton(key);
		const lcText = _.toLower(key);
		const newData = _.filter(_.sortBy(filterBarangay, ['brgyDesc']), ({ brgyDesc: name }) => {
			const lcName = _.toLower(name);
			return (
				lcName.indexOf(lcText) > -1 ||
				lcText.indexOf(lcName) > -1
			);
		});
		const noResult = i18n.t('common.noResult');
		const noItemsData = [{
			name: noResult, displayName: noResult, spellings: '', noCheck: true,
		}];
		const nonEmptyData = newData.length === 0 ? noItemsData : newData;
		this.setState({ options: nonEmptyData, locationFilter: key });
	}

	resetField = () => {
		const { reset } = this.props;
		const key = '';
		reset();
		this.updateCountryList(key);
		this.checkCrossButton();
	}

	render() {
		const { options, barangay } = this.state;
		const valueKey = 'id';
		const labelKey = 'brgyDesc';
		return (
			<View style={[styles.container, this.getSafeMargin()]}>
				<View style={styles.locationPickerList}>
					<TextInput
						checkIfFormHasValue={this.state.fieldHasValue}
						name="locationBar"
						testID="tiLocationBar"
						autoCapitalize="none"
						placeholder="Search any keyword"
						autoCorrect
						returnKeyType="go"
						keyboardType={(isAndroid) ? 'default' : 'ascii-capable'}
						value={this.state.locationFilter}
						defaultText={this.state.locationFilter}
						style={styles.locationPickerTextBox}
						removeText={() => this.resetField()}
						onChange={(text) => this.updateList(text)}
					/>
				</View>
				<FlatList
					ref={(ref) => { this.flatListRef = ref; }}
					style={styles.listContainer}
					data={options}
					keyExtractor={(option) => `${option[valueKey]}`}
					inverted={false}
					renderItem={({ item, index }) => {
						const l = item[labelKey];
						const v = item[valueKey];
						const isSelected = (_.isEqual(v, barangay.id));
						return (
							<TouchableOpacity
								style={[
									styles.option,
									index === options.length - 1 && styles.lastOption,
								]}
								key={v}
								onPress={() => { this.selectItem(item); }}
								disabled={_.isEqual(l, i18n.t('common.noResult'))}
							>
								<View style={[
									styles.optionLabel,
								]}
								>
									<Text
										textStyle="subhead"
										color={isSelected ? basicColor.wrikeGreen2 : basicColor.wrikeBg }
										numberOfLines={2}
									>{l}
									</Text>
									{!_.isEmpty(item.withIcon) &&
										<Icon name={item.withIcon} color={isSelected ? 'textBlue' : 'textMistBlue'} style={styles.optionIcon} />}
								</View>
								{/* {isSelected && <Icon name="check" testID="Check" color={basicColor.wrikeGreen2} />} */}
							</TouchableOpacity>
						);
					}}
				/>
			</View>
		);
	}
}

const onSubmit = (values, dispatch, ownProps) => (
	new Promise(() => {
		const { navigation } = ownProps;
		navigation.goBack(null);
	})
);

const onSubmitSuccess = () => {};

const FormContainer = reduxForm({
	form: 'BarangaySelection',
	onSubmit,
	onSubmitSuccess,
})(BarangaySelection);

export { FormContainer };
export default connect(null, null)(FormContainer);
