import React from 'react';
import {
  ListGroup,
  ListGroupItem,
} from 'reactstrap';
import PropTypes from 'prop-types';
import {
  Link,
} from 'react-router-dom';
import strToSlug from '../StrToSlug';

import '../css/Vegetables.css';

class Vegetables extends React.Component {
  constructor(props) {
    super(props);

    const {
      selectedType,
      selectVegetable,
    } = this.props;

    this.state = {
      selectedType,
      selectedVegetable: selectVegetable,
    };

    this.goTo = this.goTo.bind(this);
  }

  componentWillReceiveProps(newProps) {
    this.setState(newProps);
  }

  createLink(vegetable) {
    const {
      selectedType,
    } = this.state;

    let url = '/vegetaux/';
    if (vegetable.Type) {
      url += `${vegetable.Type.id}-${strToSlug(vegetable.Type.name)}`;
    } else {
      url += `${selectedType.id}-${strToSlug(selectedType.name)}`;
    }
    url += `/${vegetable.id}-${strToSlug(vegetable.name)}`;

    return url;
  }

  goTo(vegetable) {
    const {
      history,
    } = this.props;

    const url = this.createLink(vegetable);
    history.push(url);
  }

  render() {
    const {
      double,
      simple,
      selectVegetable,
    } = this.props;

    const {
      selectedType,
      selectedVegetable,
    } = this.state;

    let addClass = 'triple';

    if (simple) {
      addClass = '';
    } else if (double) {
      addClass = 'double';
    }

    return (
      <div className="with-margin">
        <div className=" with-border with-background">
          <ListGroup className={`vegetables--types--group ${addClass}`}>
            {
              selectedType
              && selectedType.Vegetables
              && selectedType.Vegetables.map(vegetable => (
                <ListGroupItem
                  key={vegetable.id}
                  className={selectedVegetable.id === vegetable.id ? 'selected' : 'null'}
                  onMouseOver={() => selectVegetable(vegetable)}
                  onClick={() => this.goTo(vegetable)}
                  onFocus={() => { }}
                >
                  <Link to={this.createLink(vegetable)}>
                    {vegetable.name}
                  </Link>

                </ListGroupItem>
              ))
            }
          </ListGroup>
        </div>
      </div>
    );
  }
}

Vegetables.defaultProps = {
  double: false,
  simple: false,
};

Vegetables.propTypes = {
  double: PropTypes.bool,
  simple: PropTypes.bool,
  selectedType: PropTypes.shape().isRequired,
  selectVegetable: PropTypes.shape().isRequired,
  history: PropTypes.shape().isRequired,
};

export default Vegetables;
