import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	Dropdown as SemanticDropdown,
	Label as SemanticLabel,
	Popup as SemanticPopup,
	Icon as SemanticIcon
} from 'semantic-ui-react';

import * as styles from './Style.less';

export default class FilterSimple extends Component {
	static propTypes = {
		title: PropTypes.string.isRequired,
		defaultLabel: PropTypes.string,
		options: PropTypes.array.isRequired,
		multiple: PropTypes.bool,
		onChange: PropTypes.func,
		noReset: PropTypes.bool,
		width: PropTypes.oneOf(['thin', 'normal'])
	};

	static defaultProps = {
		defaultLabel: 'All',
		multiple: false,
		onChange: null,
		noReset: false,
		width: 'normal'
	};

	static createOptions(options) {
		const items = [];

		let numGroups = 0;
		options.forEach((option) => {
			if (option.options) {
				if (option.options.length > 0) {
					const opt = {
						text: option.text,
						key: option.text,
						disabled: true,
						className: styles.Header
					};

					items.push(opt);

					option.options.forEach((suboption) => {
						items.push(Object.assign(suboption, { key: suboption.value }));
					});

					numGroups += 1;
				}
			} else {
				items.push(option);
			}
		});

		// remove header if only one group
		if (numGroups === 1) {
			items.shift();
		}

		return items;
	}

	constructor(props) {
		super(props);

		let value = [];
		props.options.forEach((o) => {
			if (o.options) {
				value.push(...o.options.filter(o_ => o_.active).map(o_ => o_.value));
			} else if (o.active) {
				value.push(o.value);
			}
		});

		if (!props.multiple) {
			value = value[0]; // eslint-disable-line prefer-destructuring
		}

		this.state = {
			visible: false,
			options: FilterSimple.createOptions(props.options),
			value,
			searchQuery: '',
			searching: false
		};
	}

	onChange(e, { value }) {
		this.setState({
			value,
			searchQuery: '',
			searching: false,
			visible: this.props.multiple
		}, () => {
			if (this.props.multiple) {
				// force selection to known state to avoid error
				const index = this.state.options.findIndex(o => !o.disabled) || 0;
				this.dropdown.setState({ selectedIndex: index });
			} else {
				this.props.onChange(value);
			}
		});
	}

	onSearch(e, { searchQuery }) {
		this.setState({
			searchQuery,
			searching: searchQuery.length
		});
	}

	getLabel() {
		let label = this.props.defaultLabel;
		let color = 'grey';

		if (this.props.multiple) {
			if (this.state.value.length > 0) {
				color = 'blue';
				if (this.state.value.length === 1) {
					label = this.state.options.find(e => e.value === this.state.value[0]).text;
				} else {
					label = this.state.value.length;
				}
			}
		} else if (this.state.value) {
			label = this.state.options.find(e => e.value === this.state.value).text;
			color = 'blue';
		}

		return { label, color };
	}

	render() {
		const label = this.getLabel();

		return (
			<div className={styles.FilterSimple}>
				<h5>
					{this.props.title}
				</h5>
				<SemanticPopup
					className={styles.Popup}
					on="click"
					open={this.state.visible}
					onOpen={() => this.setState({ visible: true })}
					onClose={() => {
						this.setState({
							visible: false
						}, () => {
							if (this.props.multiple) {
								this.props.onChange(this.state.value);
							}
						});
					}}
					position="bottom left"
					verticalOffset={10}
					trigger={(
						<SemanticLabel color={label.color}>
							{label.label}
							{
								((!this.props.multiple && this.state.value) || (this.props.multiple && this.state.value.length > 0)) && !this.props.noReset && (
									<SemanticIcon
										name="times"
										onClick={(e) => {
											e.stopPropagation();
											this.setState({
												value: this.props.multiple ? [] : ''
											}, () => {
												this.props.onChange(this.props.multiple ? [] : '');
											});
										}}
									/>
								)
							}
						</SemanticLabel>
					)}
				>
					<SemanticDropdown
						ref={(element) => { this.dropdown = element; }}
						className={`${styles.Dropdown}${this.props.multiple ? ' multiple' : ''}${this.state.searching ? ' searching' : ''} ${this.props.width}`}
						open
						search
						searchInput={{ autoFocus: true }}
						searchQuery={this.state.searchQuery}
						selection
						clearable
						selectOnBlur={false}
						selectOnNavigation={false}
						multiple={this.props.multiple}
						options={this.state.options}
						value={this.state.value}
						onChange={(e, o) => this.onChange(e, o)}
						onSearchChange={(e, o) => this.onSearch(e, o)}
					/>
				</SemanticPopup>
			</div>
		);
	}
}
