import React from 'react';
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';

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

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

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

    this.getVegetables();
    this.props.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,
          },
          vegetables: res.data.rows,
        });
      })
      .catch(() => {
        NotificationManager.error('Erreur lors de la récupération des catégories');
      });
  }

  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="12">
                <Vegetables
                  selectedType={this.state.selectedType}
                  selectedVegetable={this.state.selectedVegetable}
                  selectVegetable={this.selectVegetable}
                  simple={true}
                />
              </Col>
            </Row>
          </Col>
        </Row>
      </Container>
    );
  }
}
