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

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

    this.state = {
      typeId: props.match.params.typeId,
      vegetableId: props.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.renderProperty = this.renderProperty.bind(this);

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

  onExiting() {
    this.animating = true;
  }

  onExited() {
    this.animating = false;
  }

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

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

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

  getItem() {
    Api.get(`/types/${this.state.typeId}/vegetables/${this.state.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');
      });
  }

  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={this.state.item.Pictures} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
            {this.state.item &&
              this.state.item.Pictures &&
              this.state.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>);
  }

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

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

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

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

  formatValue(value) {

    if (!value) {
      return (null)
    }

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

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

    return (
      <ListGroupItem key={key}>
        <strong>{item.Property.name}</strong> : {this.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(this.renderProperty)}
    </ListGroup>)
  }

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

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

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

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

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