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

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

export default class FilterDate extends Component {
	static propTypes = {
		omit: PropTypes.array,
		onChange: PropTypes.func
	};

	static defaultProps = {
		omit: [],
		onChange: null
	};

	constructor(props) {
		super(props);

		this.intervals = [
			{
				text: '7 Days',
				value: '7'
			},
			{
				text: '14 Days',
				value: '14'
			},
			{
				text: '30 Days',
				value: '30'
			},
			{
				text: '60 Days',
				value: '60'
			},
			{
				text: '90 Days',
				value: '90'
			},
			{
				text: '6 Months',
				value: '180'
			},
			{
				text: 'Year',
				value: '365'
			},
			{
				text: 'All Time',
				value: 'alltime'
			}
		];

		this.state = {
			intervals: null,
			value: null,
			visible: false
		};
	}

	componentDidMount() {
		this.createOptions(this.props.omit);
	}

	componentWillReceiveProps(nextProps) {
		this.createOptions(nextProps.omit);
	}

	onChange(value) {
		if (value !== localStorage.getItem('interval')) {
			localStorage.setItem('interval', value);

			this.setState({
				value,
				visible: false
			}, () => {
				this.props.onChange(value);
			});
		}
	}

	createOptions(omit) {
		const intervals = this.intervals.filter(interval => !omit.includes(interval.value));
		const value = !omit.includes(localStorage.getItem('interval')) ? (localStorage.getItem('interval') || intervals[0].value) : intervals[0].value;

		this.setState({
			intervals,
			value
		});
	}

	render() {
		if (this.state.intervals) {
			const label = this.state.intervals.filter(interval => interval.value === this.state.value)[0].text;

			return (
				<div className={styles.FilterDate}>
					{
						this.state.intervals && (
							<SemanticPopup
								className={styles.Popup}
								on="click"
								open={this.state.visible}
								onOpen={() => this.setState({ visible: true })}
								onClose={() => this.setState({ visible: false })}
								position="bottom left"
								verticalOffset={10}
								trigger={(
									<SemanticLabel>
										{label}
									</SemanticLabel>
								)}
							>
								<SemanticDropdown
									className={styles.Dropdown}
									open
									selection
									selectOnBlur={false}
									selectOnNavigation={false}
									options={this.state.intervals}
									value={this.state.value}
									onChange={(e, { value }) => {
										setTimeout(() => this.onChange(value), 50);
									}}
								/>
							</SemanticPopup>
						)
					}
					<SemanticIcon
						name="calendar alternate"
					/>
				</div>
			);
		}

		return <React.Fragment />;
	}
}
