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 Vegetables from '../Components/Vegetables';

class Search extends React.Component {
  constructor(props) {
    super(props);
    const {
      match,
      changeBackground,
    } = props;

    this.state = {
      query: match.params.query || null,
      selectedType: {},
      selectedVegetable: {},
    };

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

    this.getVegetables();
    changeBackground('map');
  }

  getVegetables() {
    const {
      query,
    } = this.state;

    Api.get(`search/vegetables/?q=${query}`)
      .then((res) => {
        this.setState({
          selectedType: {
            Vegetables: res.data.rows,
            id: res.data.rows.length > 0 ? res.data.rows[0].Type.id : null,
            name: res.data.rows.length > 0 ? res.data.rows[0].Type.name : null,
          },
        });
      })
      .catch(() => {
        NotificationManager.error('Erreur lors de la récupération des catégories');
      });
  }

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

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

    return (
      <Container>
        <NotificationContainer />
        <Row>
          <Col xs="12" sm="8">
            <MapItem
              selectedType={selectedType}
              selectedVegetable={selectedVegetable}
              selectVegetable={this.selectVegetable}
            />
          </Col>
          <Col xs="12" sm="4">
            <Row>
              <Col xs="12">
                <Vegetables
                  selectedType={selectedType}
                  selectedVegetable={selectedVegetable}
                  selectVegetable={this.selectVegetable}
                  simple
                  history={history}
                />
              </Col>
            </Row>
          </Col>
        </Row>
      </Container>
    );
  }
}

Search.defaultProps = {
  match: {
    params: {
      query: null,
    },
  },
};

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

export default Search;
