/* eslint-disable guard-for-in*/
import React, { Component } from 'react';
import { Link } from 'react-router';

import Helmet from 'react-helmet';
import { helmet } from 'core/config/constants';

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import * as PropertiesActions from 'core/actions/properties/properties';
import * as FilterActions from 'jqestate.ru/actions/filter';
import * as OrderActions from 'jqestate.ru/actions/order';
import * as PaginationActions from 'jqestate.ru/actions/pagination';

import List from 'jqestate.ru/components/properties/list';
import Filter from 'jqestate.ru/components/properties/filter';
import OrderBy from 'jqestate.ru/components/order-by';
import Pagination from 'jqestate.ru/components/pagination';

import RequestBanner from 'jqestate.ru/components/banners/request';

import UI from 'jqestate.ru/components/ui';
import 'jqestate.ru/styles/properties/main';

function promisify(fn) {
  return Promise.resolve(fn);
}

class PropertiesContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      filterOpen: false,
      orderByOpen: false,
    };
  }

  componentWillMount() {
    const { filter, pagination, orderBy } = this.props;

    this.load({ filter, pagination, orderBy });
  }

  componentWillReceiveProps(props) {
    const { filter, pagination, orderBy, params } = props;
    const { kind, dealType } = params;

    if (this.props.params.dealType !== dealType) {
      this.load({ filter, pagination, orderBy }, kind, dealType);
    } else {
      let filterCount = 0;
      const filterObj = props.filter[kind + dealType];

      for (const key in filterObj) {
        const prop = filterObj[key];

        if (filterObj.hasOwnProperty(key) && prop) {
          if (Array.isArray(prop) && !prop.length) continue;

          filterCount++;
        }
      }

      this.setState({
        filterCount,
      });
    }
  }

  load(params = {}, kind = this.props.params.kind, dealType = this.props.params.dealType) {
    const { filter = {}, pagination = {}, orderBy = {} } = params;

    const defaults = {
      filter: {
        state: `public`,
        'deals.dealType': dealType,
      },
      pagination: {
        limit: 24,
      },
    };

    this.props.actions.loadProperties(kind, {
      filter: {
        ...defaults.filter,
        ...filter[kind + dealType],
      },
      pagination: {
        ...defaults.pagination,
        ...pagination[kind + dealType],
      },
      orderBy: {
        ...defaults.orderBy,
        ...orderBy[kind + dealType],
      },
    });
  }

  handleOrderByUpdate(field, predicate) {
    const { dealType, kind } = this.props.params;
    const properties = this.props.properties[kind] || {};
    const { pagination = {} } = properties;

    if (pagination.offset > 0) {
      Promise.all([
        promisify(this.props.actions.updateOrder(field, predicate, kind, dealType)),
        promisify(this.props.actions.updatePagination(0, kind, dealType)),
      ]).then(() => this.load(this.props));
    } else {
      Promise.resolve(
        this.props.actions.updateOrder(field, predicate, kind, dealType)
      ).then(() => this.load(this.props));
    }
  }

  handleFilterUpdate(ref, value) {
    const { dealType, kind } = this.props.params;
    const properties = this.props.properties[kind] || {};
    const { pagination = {} } = properties;

    if (pagination.offset > 0) {
      Promise.all([
        promisify(this.props.actions.updatePagination(0, kind, dealType)),
        promisify(this.props.actions.updateFilter(ref, value, kind, dealType)),
      ]).then(() => this.load(this.props));
    } else {
      promisify(
        this.props.actions.updateFilter(ref, value, kind, dealType)
      ).then(() => this.load(this.props));
    }
  }

  resetFilter() {
    const { dealType, kind } = this.props.params;
    window.scrollTo(0, 0);

    Promise.all([
      promisify(this.props.actions.updatePagination(0, kind, dealType)),
      promisify(this.props.actions.resetFilter(kind, dealType)),
    ]).then(() => this.load(this.props));
  }

  resetOrder() {
    const { dealType, kind } = this.props.params;
    window.scrollTo(0, 0);

    Promise.all([
      promisify(this.props.actions.updatePagination(0, kind, dealType)),
      promisify(this.props.actions.resetOrder(kind, dealType)),
    ]).then(() => this.load(this.props));
  }

  handlePaginationUpdate(offset) {
    const { dealType, kind } = this.props.params;
    window.scrollTo(0, 0);

    promisify(
      this.props.actions.updatePagination(offset, kind, dealType)
    ).then(() => this.load(this.props));
  }

  toggleDropdown(key) {
    this.setState({
      [key]: !this.state[key],
    });
  }

  render() {
    const { kind, dealType } = this.props.params;
    const properties = this.props.properties[kind] || {};
    const orderBy = this.props.orderBy[kind + dealType] || {};
    const filter = this.props.filter[kind + dealType] || {};
    const { items = [], isFetching = false, pagination = {} } = properties;

    const { filterCount } = this.state;

    return (
      <section className="properties">
        <Helmet
          title={helmet.properties[dealType].title}
          meta={[
            { name: `description`, content: helmet.properties[dealType].description },
            { name: `keywords`, content: helmet.properties[dealType].keywords },
          ]}
        />

        <UI.Container>
          <UI.Row>
            <UI.Container>
              <UI.Row>
                <section className="properties-row clearfix">
                  <div className="col-sm-2 hidden-xs">
                    <UI.Header className="properties-row-title">Найдено {pagination.total}</UI.Header>
                  </div>
                  <div className="col-sm-2 col-sm-offset-3 text-center">
                    <div className="properties-row-btn-group btn-group" role="group">
                      <Link className="properties-row-btn-group-btn btn" activeClassName="active" to={`/properties/${kind}/sale`}>Купить</Link>
                      <Link className="properties-row-btn-group-btn btn" activeClassName="active" to={`/properties/${kind}/rent`}>Снять</Link>
                    </div>
                  </div>
                  <div className="col-sm-5 text-right properties-row-filter-xs">
                    <OrderBy update={::this.handleOrderByUpdate} reset={::this.resetOrder} isOpen={this.state.orderByOpen} orderBy={orderBy} fields={[`deals.multiCurrencyPrice.usd`, `location.mkadDistance`, `landProperty.area`, `objectProperty.area`]} />
                    <Filter update={::this.handleFilterUpdate} reset={::this.resetFilter} isOpen={this.state.filterOpen} toggleDropdown={this.toggleDropdown.bind(this, `filterOpen`)} value={filter} dealType={dealType} count={filterCount} />
                  </div>
                </section>
              </UI.Row>
            </UI.Container>
          </UI.Row>
          <UI.Row>
            <List items={items} isFetching={isFetching} kind={kind} dealType={dealType} cardSize={"col-sm-6 col-md-4 col-lg-3"} />
          </UI.Row>
          <UI.Row>
            <div className="col-sm-6 col-sm-offset-3 text-center">
              <Pagination total={pagination.total} offset={pagination.offset} limit={pagination.limit} update={::this.handlePaginationUpdate} />
            </div>
          </UI.Row>
          {items.length > 0 &&
            <UI.Row>
              <div className="col-xs-12">
                <RequestBanner />
              </div>
            </UI.Row>
          }
        </UI.Container>

        {/* <UI.Button kind="primary" size="xlg" block className="visible-xs filter-btn-xs" onClick={this.toggleDropdown.bind(this, `orderByOpen`)}>Сортировка</UI.Button> */}
        <UI.Button kind="primary" size="xlg" block className="visible-xs filter-btn-xs" onClick={this.toggleDropdown.bind(this, `filterOpen`)}>Фильтр{filterCount ? ` (${filterCount})` : ``}</UI.Button>
      </section>
    );
  }
}

const pickState = ({ properties, filter, orderBy, pagination }) => ({
  properties, filter, orderBy, pagination,
});

const pickActions = (dispatch) => ({
  actions: bindActionCreators({
    ...PropertiesActions,
    ...FilterActions,
    ...OrderActions,
    ...PaginationActions,
  }, dispatch),
});

export default connect(pickState, pickActions)(PropertiesContainer);
