import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tag } from '@icedesign/base';
import './TagGroup.scss';

export default class TagGroup extends Component {

  static propTypes = {
    dataSource: PropTypes.array,
    value: PropTypes.array,
    onChange: PropTypes.func
  };

  static defaultProps = {
    dataSource: [],
    value: [],
    onChange: () => {}
  };

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

  componentWillReceiveProps(nextProps) {
    if (nextProps.hasOwnProperty('value')) {
      this.setState({
        value: nextProps.value
      });
    }
  }

  tagSelectHandler = (tagValue, selected) => {

    let {value} = this.state;

    if (selected) {
      value.push(tagValue);
    } else {
      const index = value.indexOf(tagValue);
      value.splice(index, 1);
    }

    this.setState({
      value
    });

    this.props.onChange(value);
  };


  render() {

    const {dataSource, className, onChange, style, ...others} = this.props;
    const {value} = this.state;
    const cls = 'ice-tag-group ' + (className || '');

    return (
      <div className={cls} style={style}>
        {
          dataSource.map((item, idx) => {
            const {value: tagValue, ...others} = item;
            const label = item.label || tagValue;

            const selected = value.indexOf(tagValue) > -1;

            return (
              <Tag
                {...others}
                key={idx}
                value={tagValue}
                selected={selected}
                size="small"
                onSelect={this.tagSelectHandler.bind(this, tagValue)}
              >
                {label}
              </Tag>
            );
          })
        }
      </div>
    );
  }
}
