import React from 'react';
import PropTypes from 'prop-types';
import {
  Container,
  Row,
  Col,
  ListGroup,
  ListGroupItem,
  Carousel,
  CarouselItem,
  CarouselControl,
  CarouselIndicators,
  Breadcrumb,
  BreadcrumbItem,
} from 'reactstrap';
import {
  NotificationContainer,
  NotificationManager,
} from 'react-notifications';
import Api from '../Components/Api';
import MapItem from '../Components/Map';
import strToSlug from '../StrToSlug';

class RouterVegetable extends React.Component {
  static formatValue(value) {
    if (!value) {
      return (null);
    }

    if (value[0] === '*') {
      return (<div className="tabbed" dangerouslySetInnerHTML={{ __html: value.replace('*', '- ').replace(/\*/g, '<br />- ') }} />);
    }
    return value;
  }

  constructor(props) {
    super(props);
    const {
      match,
      changeBackground,
    } = props;

    this.state = {
      typeId: match.params.typeId,
      vegetableId: match.params.vegetableId,
      selectedType: {
        name: '',
        Vegetables: [],
      },
      item: {
        name: null,
        Type: {
          id: null,
          name: null,
        },
      },
      activeIndex: 0,
      carouselHeight: 0,
    };

    this.getItem = this.getItem.bind(this);
    this.next = this.next.bind(this);
    this.previous = this.previous.bind(this);
    this.goToIndex = this.goToIndex.bind(this);
    this.onExiting = this.onExiting.bind(this);
    this.onExited = this.onExited.bind(this);
    this.setHeight = this.setHeight.bind(this);

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

  onExiting() {
    this.animating = true;
  }

  onExited() {
    this.animating = false;
  }

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

    Api.get(`/types/${typeId}/vegetables/${vegetableId}`)
      .then((res) => {
        this.setState({
          selectedType: {
            id: res.data.Type.id,
            name: res.data.Type.name,
            Vegetables: [
              res.data,
            ],
          },
          item: res.data,
        });
      })
      .catch(() => {
        NotificationManager.error('Erreur lors de la récupération du végétal');
      });
  }

  setHeight(height) {
    this.setState({
      carouselHeight: height,
    });
  }

  goToIndex(newIndex) {
    if (this.animating) return;
    this.setState({ activeIndex: newIndex });
  }

  next() {
    const {
      activeIndex,
      item,
    } = this.state;

    if (this.animating) return;
    const nextIndex = activeIndex === item.Pictures.length - 1 ? 0 : activeIndex + 1;
    this.setState({ activeIndex: nextIndex });
  }

  previous() {
    const {
      activeIndex,
      item,
    } = this.state;

    if (this.animating) return;
    const nextIndex = activeIndex === 0 ? item.Pictures.length - 1 : activeIndex - 1;
    this.setState({ activeIndex: nextIndex });
  }

  renderCarousel() {
    const {
      activeIndex,
      item,
      carouselHeight,
    } = this.state;

    if (!item || !item.Pictures || item.Pictures.length === 0) {
      return (null);
    }

    return (
      <Col xs="12" lg="6">
        <Row className="with-margin">
          <Col className="with-border with-background">
            <Carousel
              activeIndex={activeIndex}
              next={this.next}
              previous={this.previous}
            >
              <CarouselIndicators
                items={item.Pictures}
                activeIndex={activeIndex}
                onClickHandler={this.goToIndex}
              />
              {item
                && item.Pictures
                && item.Pictures.map(picture => (
                  <CarouselItem
                    onExiting={this.onExiting}
                    onExited={this.onExited}
                    key={picture.url}
                  >
                    <img src={picture.url} alt={picture.url} style={{ maxHeight: `${carouselHeight}px` }} />
                  </CarouselItem>
                ))}
              <CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} />
              <CarouselControl direction="next" directionText="Next" onClickHandler={this.next} />
            </Carousel>
          </Col>
        </Row>
      </Col>
    );
  }

  renderMap() {
    const {
      item,
      selectedType,
    } = this.state;

    const sm = (!item || !item.Pictures || item.Pictures.length === 0) ? 12 : 6;

    return (
      <Col xs="12" lg={sm}>
        <MapItem
          selectedType={selectedType}
          selectedVegetable={item}
          selectVegetable={() => { }}
          setHeight={this.setHeight}
        />
      </Col>
    );
  }

  static renderProperty(item, key) {
    if (item.Property === null || item.Property === undefined || !item.value) {
      return (null);
    }

    return (
      <ListGroupItem key={key}>
        <strong>{item.Property.name}</strong>
        {' '}
        :
        {' '}
        {RouterVegetable.formatValue(item.value)}
      </ListGroupItem>
    );
  }

  renderProperties() {
    const {
      item,
    } = this.state;

    if (!item.Properties
      || !item.Properties.length === 0
    ) {
      return (null);
    }

    return (
      <ListGroup className="double">
        {item.Properties.map(RouterVegetable.renderProperty)}
      </ListGroup>
    );
  }

  render() {
    const {
      item,
    } = this.state;

    return (
      <Container>
        <NotificationContainer />
        <Row>
          <Col xs="12">
            <Row className="with-margin">
              <Col className="no-padding">
                <Breadcrumb>
                  <BreadcrumbItem><a href={`/vegetaux/${item.Type.id}-${strToSlug(item.Type.name)}`}>{item.Type.name}</a></BreadcrumbItem>
                  <BreadcrumbItem active>{item.name}</BreadcrumbItem>
                </Breadcrumb>

              </Col>
            </Row>
          </Col>
          {this.renderMap()}
          {this.renderCarousel()}
          <Col xs="12">
            <Row className="with-margin">
              <Col className=" with-border with-background">
                {this.renderProperties()}

              </Col>
            </Row>
          </Col>

        </Row>
      </Container>
    );
  }
}

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

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

export default RouterVegetable;
