import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
	Tab as SemanticTab,
	Menu as SemanticMenu,
	Label as SemanticLabel
} from 'semantic-ui-react';

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

export default class Tabs extends Component {
	static propTypes = {
		id: PropTypes.string,
		panes: PropTypes.array.isRequired,
		rightPane: PropTypes.object,
		onTabChange: PropTypes.func
	};

	static defaultProps = {
		id: null,
		rightPane: null,
		onTabChange: () => {}
	};

	static createPanes(panes) {
		const arr = [];

		panes.forEach((pane) => {
			arr.push({
				menuItem: (
					<SemanticMenu.Item
						className={styles.Tab}
						key={pane.title}
					>
						{pane.title}
						{
							typeof pane.count !== 'undefined' && (
								<SemanticLabel
									className={styles.Count}
								>
									{pane.count}
								</SemanticLabel>
							)
						}
					</SemanticMenu.Item>
				),
				pane: (
					<SemanticTab.Pane
						className={styles.Pane}
						attached="bottom"
						key={pane.title}
					>
						{pane.pane}
					</SemanticTab.Pane>
				)
			});
		});

		return arr;
	}

	static createRightPane(pane) {
		return {
			menuItem: (
				<SemanticMenu.Item
					className={`${styles.Tab} right`}
					key="rightContentMenu"
				>
					{pane.title}
				</SemanticMenu.Item>
			),
			pane: (
				<SemanticTab.Pane
					className={styles.Pane}
					attached="bottom"
					key="rightContentPane"
				>
					{pane.pane}
				</SemanticTab.Pane>
			)
		};
	}

	constructor(props) {
		super(props);

		let defaultActiveIndex = 0;
		if (this.props.id) {
			let tabStorage = localStorage.getItem('tab');
			if (tabStorage) {
				tabStorage = JSON.parse(tabStorage);
				defaultActiveIndex = tabStorage[this.props.id] || 0;
			}
		}

		const panes = Tabs.createPanes(props.panes);

		if (props.rightPane) {
			panes.push(Tabs.createRightPane(props.rightPane));
		}

		this.state = {
			defaultActiveIndex,
			panes
		};
	}

	componentWillReceiveProps(nextProps) {
		const panes = Tabs.createPanes(nextProps.panes);

		if (nextProps.rightPane) {
			panes.push(Tabs.createRightPane(nextProps.rightPane));
		}

		this.setState({
			panes
		});
	}

	onTabChange(e, index) {
		this.props.onTabChange(e, index);

		if (this.props.id) {
			let tabStorage = localStorage.getItem('tab');
			if (tabStorage) {
				tabStorage = JSON.parse(tabStorage);
				tabStorage[this.props.id] = index;
			} else {
				tabStorage = {
					[this.props.id]: index
				};
			}

			localStorage.setItem('tab', JSON.stringify(tabStorage));
		}
	}

	render() {
		return (
			<SemanticTab
				className={styles.Tabs}
				renderActiveOnly={false}
				defaultActiveIndex={this.state.defaultActiveIndex}
				onTabChange={(e, d) => {
					this.onTabChange(e, d.activeIndex);
				}}
				menu={{
					secondary: true,
					pointing: true,
					attached: 'top'
				}}
				panes={this.state.panes}
			/>
		);
	}
}
