import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	Breadcrumb as SemanticBreadcrumb,
	Dropdown as SemanticDropdown
} from 'semantic-ui-react';

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

export default class Breadcrumb extends Component {
	static propTypes = {
		path: PropTypes.array.isRequired,
		onChange: PropTypes.func
	};

	static defaultProps = {
		onChange: null
	};

	constructor(props) {
		super(props);

		this.state = {
			path: props.path
		};
	}

	render() {
		const { length } = this.state.path;

		return (
			<SemanticBreadcrumb
				className={styles.Breadcrumb}
			>
				{
					this.state.path.map((item, i) => {
						let node;

						if (item.options) {
							node = (
								<SemanticDropdown
									inline
									scrolling
									pointing="top left"
									search={item.search || false}
									selectOnNavigation={false}
									selectOnBlur={false}
									options={item.options}
									defaultValue={item.options.find(({ active }) => active) ? item.options.find(({ active }) => active).value : item.options[0].value}
									onChange={(e, data) => {
										setTimeout(() => {
											item.onChange ? item.onChange(e, data) : this.props.onChange(e, data); // eslint-disable-line no-unused-expressions
										}, 50);
									}}
								/>
							);
						} else if (item.link) {
							node = React.cloneElement(
								item.link,
								null,
								item.title
							);
						} else {
							node = item.title;
						}

						return (
							<React.Fragment
								key={item.title || 'node'}
							>
								<SemanticBreadcrumb.Section
									active={i === (length - 1)}
								>
									{node}
								</SemanticBreadcrumb.Section>
								{
									i < (length - 1) && (
										<SemanticBreadcrumb.Divider
											icon="right angle"
										/>
									)
								}
							</React.Fragment>
						);
					})
				}
			</SemanticBreadcrumb>
		);
	}
}
