import React from 'react';
import {
  Container,
  Row,
  Col,
  ListGroup,
  ListGroupItem,
  Badge,
} from 'reactstrap';
import {
  NotificationContainer,
  NotificationManager,
} from 'react-notifications';
import Api from '../Components/Api';
import MapItem from '../Components/Map';
import Vegetables from '../Components/Vegetables';

export default class RouterMap extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      types: [],
      vegetables: [],
      selectedType: {},
      selectedVegetable: {},
    };

    this.getVegetablesTypes = this.getVegetablesTypes.bind(this);
    this.selectType = this.selectType.bind(this);
    this.selectVegetable = this.selectVegetable.bind(this);

    this.getVegetablesTypes();
    this.props.changeBackground('map')
  }

  getVegetablesTypes() {
    Api.get('types')
      .then((res) => {
        this.setState({
          types: res.data.rows,
        });
      })
      .catch(() => {
        NotificationManager.error('Erreur lors de la récupération des catégories');
      });
  }

  selectType(type) {
    this.setState({
      selectedType: type,
    });
  }

  selectVegetable(vegetable) {
    this.setState({
      selectedVegetable: vegetable,
    });
  }

  render() {
    return (
      <Container>
        <NotificationContainer />
        <Row>

          <Col xs="12" sm="8">
            <MapItem
              selectedType={this.state.selectedType}
              selectedVegetable={this.state.selectedVegetable}
              selectVegetable={this.selectVegetable}
            />
          </Col>
          <Col xs="12" sm="4">
            <Row>
              <Col xs="6" sm="12">
                <div className="with-margin">
                  <div className=" with-border with-background">
                    <ListGroup className="vegetables--types--group">
                      {
                        this.state.types.map((type, key) => (
                          <ListGroupItem
                            key={key}
                            className={this.state.selectedType.id === type.id ? 'selected' : 'null'}
                            onClick={e => this.selectType(type)}
                          >
                            {type.name}
                            <Badge pill>{type.Vegetables.length}</Badge>
                          </ListGroupItem>
                        ))
                      }
                    </ListGroup>
                  </div>
                </div>
              </Col>
            </Row>
          </Col>

          <Col xs="12" sm="12">
            <Vegetables
              selectedType={this.state.selectedType}
              selectedVegetable={this.state.selectedVegetable}
              selectVegetable={this.selectVegetable}
            />
          </Col>
        </Row>
      </Container>
    );
  }
}
