import React, { Component, PropTypes } from 'react';
import utils from '@dtrussia/utils.js';

import UI from 'jqestate.ru/components/ui';
import Helmet from 'jqestate.ru/components/property/helmet';
import Navbar from 'jqestate.ru/components/property/navbar';
import Content from 'jqestate.ru/components/property/content';

// import ShareModal      from '../../modal/share';

import 'jqestate.ru/styles/property/main';

class Property extends Component {
  static propTypes = {
    id: PropTypes.string.isRequired,
    subLocality1Id: PropTypes.number.isRequired,
    property: PropTypes.object.isRequired,
    params: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    place: PropTypes.object,
    placeDetails: PropTypes.object.isRequired,
    similar: PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props);

    this.state = {
      delta: {},
    };
  }

  componentWillReceiveProps(newProps) {
    if (!this.props.property.data) {
      this.getPriceDelta(newProps);
      this.loadPlace(newProps);
    }

    // if (newProps.property.data) {
      // if (this.props.property.data && newProps.property.data && this.props.id !== newProps.id) {
        // this.getPriceDelta(newProps);
        // this.loadPlace(newProps);
      // }
    // }
  }

  getPriceDelta(props) {
    if (props.property.data && props.property.data.deals.length) {
      const deal = utils.getObjectInArray(props.property.data.deals, `dealType`, this.props.params.dealType);

      if (deal && deal.priceDelta) {
        const { priceDelta, currency } = deal;
        const price = Math.abs(priceDelta);
        const way = priceDelta > 0 ? `up` : `down`;

        this.setState({
          delta: {
            price,
            currency,
            way,
          },
        });
      }
    }
  }

  loadPlace(props) {
    if (props.property.data) {
      this.props.actions.loadPlace(`sub_localities`, props.subLocality1Id);

      // const {
        // place: {
          // timestamp,
        // } = {},
      // } = props;
      //
      // if (!this.props.place || utils.isOlderThan(timestamp)) {
        // this.props.actions.loadPlace(`sub_localities`, subLocality1Id);
      // }
    }
  }

  render() {
    const { delta } = this.state;
    const { property, params } = this.props;
    const { isFetching = true, data = {}, error } = property;

    if (isFetching) {
      return <UI.Loading />;
    }

    if (error) {
      return <div>{error}</div>;
    }

    if (data.id) {
      const { dealType, kind } = params;

      return (
        <div className="property">
          <Helmet data={data} dealType={dealType}/>
          <Navbar kind={kind} dealType={dealType} />
          <Content {...this.props} dealType={dealType} kind={kind} delta={delta} />
        </div>
      );
    }

    return null;
  }
}

export default Property;
