import React from 'react';
import { ToggleFieldWrapper } from './StyledWrappers';
import PropTypes from 'prop-types'

export default class Toggle extends React.Component {

	constructor(props) {
		super(props)
		this.state = {
			selected: props.selected || null
		};
	}

	componentWillReceiveProps(np) {
		if(np.selected!=undefined && np.selected!=this.props.selected) {
			this.setState({ selected: np.selected })
		}
	}

	onItemClick = (item) => {
		this.setState({ selected: item })
		if(this.props.onChange) {
			this.props.onChange(item)
		}
	}

	render() {
		return (
			<ToggleFieldWrapper className={this.props.className} themeColor={this.props.themeColor|| '#dd712f'}>
			{
				this.props.items.map( item => (
					<div
						key={item.id}
						className={`item ${this.state.selected && this.state.selected.id==item.id ? 'selected' :''} ${this.props.itemClassName || ''}`}
						onClick={this.onItemClick.bind(this, item)}
					>
						{item.label}
					</div>
				))
			}
			</ToggleFieldWrapper>
		)
	}
}

Toggle.PropTypes = {
	items: PropTypes.array.isRequired,
    selected: PropTypes.object,
    onChange: PropTypes.func,
    className: PropTypes.string,
    itemClassName: PropTypes.string
}