import React from 'react';
import PropTypes from 'prop-types';
import {
  Container,
  Row,
  Col,
} from 'reactstrap';
import {
  NotificationContainer,
  NotificationManager,
} from 'react-notifications';
import Api from '../Components/Api';
import MapItem from '../Components/Map';
import VegetablesList from '../Components/Vegetables';

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

    const {
      match,
      changeBackground,
    } = props;

    this.state = {
      typeId: match.params.typeId,
      selectedType: {},
      selectedVegetable: {},
    };

    this.getItem = this.getItem.bind(this);
    this.selectVegetable = this.selectVegetable.bind(this);

    this.getItem();
    changeBackground('vegetables');
  }

  getItem() {
    const {
      typeId,
    } = this.state;

    Api.get(`/types/${typeId}`)
      .then((res) => {
        this.setState({
          selectedType: res.data,
        });
      })
      .catch(() => {
        NotificationManager.error('Erreur lors de la récupération des végétaux');
      });
  }

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

  render() {
    const {
      history,
    } = this.props;
    const {
      selectedType,
      selectedVegetable,
    } = this.state;

    return (
      <Container>
        <NotificationContainer />
        <Row>

          <Col xs="12" md="6">
            <MapItem
              selectedType={selectedType}
              selectedVegetable={selectedVegetable}
              selectVegetable={this.selectVegetable}
            />
          </Col>
          <Col xs="12" md="6">
            <Row>
              <Col xs="12">
                <VegetablesList
                  selectedType={selectedType}
                  selectedVegetable={selectedVegetable}
                  selectVegetable={this.selectVegetable}
                  double
                  history={history}
                />
              </Col>
            </Row>
          </Col>
        </Row>
      </Container>
    );
  }
}

RouterVegetables.defaultProps = {
  match: {
    params: {
      typeId: null,
    },
  },
};

RouterVegetables.propTypes = {
  changeBackground: PropTypes.func.isRequired,
  match: PropTypes.shape({
    params: PropTypes.shape({
      typeId: PropTypes.string,
    }),
  }),
  history: PropTypes.shape().isRequired,
};

export default RouterVegetables;
