import React, { PropTypes } from 'react';
import wrap from '../ItemContainerWrapper';

import Autocomplete from '../Autocomplete';
import Checkboxes from './Checkboxes';
import CheckboxesButton from './CheckboxesButton';
import TypeSelect from './TypeSelect';
import { checkboxOptions, getCheckboxData, buildFilterItem } from './options';
import { getChickletCategory } from '../../utils';
import { KD_COUNTRY } from '../../constants';

const propTypes = {
  underneath: PropTypes.bool,
  emptyItems: PropTypes.bool,
  subWidgetRenderedInline: PropTypes.bool,
  onItemAdded: PropTypes.func,
  onItemRemoved: PropTypes.func,

  api: PropTypes.shape({
    url: PropTypes.string.isRequired,
    key: PropTypes.string.isRequired,
  }),

  kdFilterModel: PropTypes.object,
};

class KdSelectGeography extends React.Component {
  constructor(props) {
    super(props);
    this.state = { selecteds: [], type: KD_COUNTRY };

    this.changeSelecteds = this.changeSelecteds.bind(this);
    this.addCheckboxSelection = this.addCheckboxSelection.bind(this);
    this.removeCheckboxSelection = this.removeCheckboxSelection.bind(this);
    this.changeType = this.changeType.bind(this);
    this.renderCheckboxesButton = this.renderCheckboxesButton.bind(this);
    this.renderCheckboxesUnderneath = this.renderCheckboxesUnderneath.bind(this);
    this.renderAutocomplete = this.renderAutocomplete.bind(this);
  }

  componentWillReceiveProps({ emptyItems }) {
    if (emptyItems && this.props.emptyItems !== emptyItems) {
      this.setState(
        Object.assign(
          {},
          this.state,
          { selecteds: [] },
        ),
      );
    }
  }

  addCheckboxSelection(value) {
    const { selecteds, type } = this.state;

    this.setState(
      Object.assign(
        {},
        this.state,
        { selecteds: [...selecteds, value] },
      ),
      () => {
        const data = getCheckboxData(type, value);

        data.forEach((toAdd) => {
          this.props.onItemAdded({
            value: toAdd.value,
            chickletLabel: toAdd.label,
            option: toAdd.value,
            key: toAdd.value,
            category: getChickletCategory(toAdd.entityType),
          });
        });
      },
    );
  }

  removeCheckboxSelection(value) {
    const { selecteds, type } = this.state;

    this.setState(
        Object.assign(
          {},
          this.state,
          { selecteds: selecteds.filter(option => option !== value) },
        ),
        () => {
          const data = getCheckboxData(type, value);
          data.forEach((toRemove) => {
            this.props.onItemRemoved(toRemove.value);
          });
        },
      );
  }

  changeSelecteds({ value, checked }) {
    if (checked) {
      this.addCheckboxSelection(value);
    } else {
      this.removeCheckboxSelection(value);
    }
  }

  changeType(newType) {
    this.setState(
      Object.assign({}, this.state, { type: newType }),
    );
  }

  renderCheckboxesButton() {
    if (this.props.underneath) {
      return null;
    }

    return (
      <CheckboxesButton
        data={checkboxOptions}
        type={this.state.type}
        selecteds={this.state.selecteds}
        onChange={this.changeSelecteds}
      />
    );
  }

  renderCheckboxesUnderneath() {
    if (!this.props.underneath) {
      return null;
    }

    return (
      <Checkboxes
        data={checkboxOptions}
        type={this.state.type}
        selecteds={this.state.selecteds}
        onChange={this.changeSelecteds}
      />
    );
  }

  renderAutocomplete() {
    const { subWidgetRenderedInline } = this.props;
    if (subWidgetRenderedInline) {
      return null;
    }

    const { api, onItemAdded, mainSelector } = this.props;
    return (
      <div className="o-layout">
        <div className="c-kd-select-geography-container__widgets">
          {this.renderCheckboxesButton()}
          <TypeSelect
            selected={this.state.type}
            onChange={this.changeType}
          />
        </div>
        <div className="c-kd-select-geography-container__autocomplete">
          <Autocomplete
            setSelectedItems={(item) => {
              const { value, label } = item;
              onItemAdded({
                value,
                chickletLabel: label,
                option: value,
                key: value,
                category: getChickletCategory(this.state.type),
              });
            }}
            api={api}
            mainSelector={mainSelector}
            kdFilterModel={buildFilterItem(this.state.type)}
            // hasInitialValues -> poner los valores iniciales si los tiene
            // lastInicialValue -> último valor inicial si lo tiene
            // isChickletNone -> si va a agregar o solo va a dejar el display
          />
        </div>
      </div>
    );
  }

  render() {
    return (
      <div className="c-kd-select-geography-container">
        <h4>Aqui va el select main!</h4>
        {this.renderAutocomplete()}
        {this.renderCheckboxesUnderneath()}
      </div>
    );
  }
}

KdSelectGeography.propTypes = propTypes;

export default wrap(KdSelectGeography);
