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

import Autocomplete from '../Autocomplete';
import Checkboxes from './Checkboxes';
import CheckboxesButton from './CheckboxesButton';
import MainSelector from './MainSelector';
import TypeSelect from './TypeSelect';
import { checkboxOptions } from './optionsValue';
import { getCheckboxData, buildFilterItem, buildMainSelectorOptions } from './optionsHelper';
import { getChickletCategory, itemHandlerCreator } from '../../utils';
import { KD_COUNTRY } from '../../constants';

const propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  underneath: PropTypes.bool,
  emptyItems: PropTypes.bool,
  subWidgetRenderedInline: PropTypes.bool,
  onItemAdded: PropTypes.func,
  onItemRemoved: PropTypes.func,
  kdFilterModel: PropTypes.object,

  mainSelector: PropTypes.shape({
    visible: PropTypes.bool,
    selected: PropTypes.string,

    optionValues: PropTypes.shape({
      selectOption: PropTypes.shape({
        visible: PropTypes.bool,
        label: PropTypes.string,
      }),
      anyOption: PropTypes.shape({
        visible: PropTypes.bool,
        label: PropTypes.string,
      }),
      customOptions: PropTypes.array,
      userSpecifiedOption: PropTypes.shape({
        visible: PropTypes.bool,
        label: PropTypes.string,
      }),
    }),
  }),

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

  mainSelector: PropTypes.shape({
    visible: PropTypes.bool,
    selected: PropTypes.string,

    optionValues: PropTypes.shape({
      anyOption: PropTypes.shape({
        visible: PropTypes.bool,
        label: PropTypes.bool,
      }),
      specifyOption: PropTypes.shape({
        visible: PropTypes.bool,
        label: PropTypes.bool,
      }),
      customOptions: PropTypes.arrayOf(
        PropTypes.shape({
          label: PropTypes.string,
          value: PropTypes.string,
        }),
      ),
    }),
  }),
};

const defaultProps = {
  underneath: false,
  subWidgetRenderedInline: false,
  mainSelector: {
    visible: true,
    selected: 'defaultAny',
    optionValues: {
      anyOption: { visible: true },
      specifyOption: { visible: true },
      customOptions: [],
    },
  },
};

class KdSelectGeography extends React.Component {
  constructor(props) {
    super(props);

    this.mainSelector = extend(true, {}, defaultProps.mainSelector, this.props.mainSelector);
    this.state = {
      mainSelectorOptions: buildMainSelectorOptions(this.mainSelector),
      mainSelectorValue: this.mainSelector.selected,
      selecteds: [],
      type: KD_COUNTRY,
    };
  }

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

  buildItemToAdd = (item) => {
    const kdFilterOptions = {
      operator: 'Eq',
      model: this.props.kdFilterModel,
      itemHandler: itemHandlerCreator(
        item.entityType,
      ),
    };

    return {
      key: item.value,
      option: item.value,
      value: item.value,
      chickletLabel: item.label,
      category: getChickletCategory(item.entityType),
      kdFilterOptions,
    };
  }

  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(this.buildItemToAdd(toAdd));
        });
      },
    );
  }

  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 = (type) => {
    this.setState(
      Object.assign({}, this.state, { type }),
    );
  }

  changeMainSelector = (mainSelectorValue) => {
    this.setState(
      Object.assign({}, this.state, { mainSelectorValue }),
      () => {
        if (mainSelectorValue !== 'defaultAny' && mainSelectorValue !== 'defaultSpecify') {
          const { optionValues: { customOptions } } = this.mainSelector;
          const customOption = customOptions.find(option => option.value === mainSelectorValue);
          this.props.onItemAdded(this.buildItemToAdd(customOption));
        }
      }
    );
  }

  renderMainSelector = () => {
    const { mainSelector } = this.props;
    if (mainSelector && mainSelector.visible) {
      return (
        <MainSelector
          onChange={this.changeMainSelector}
          value={this.state.mainSelectorValue}
          options={this.state.mainSelectorOptions}
        />
      );
    }

    return null;
  }

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

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

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

    const { theme } = this.props;
    return (
      <Checkboxes
        theme={theme}
        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, theme } = this.props;
    return (
      <div className={classNames('o-layout', theme['o-layout'])}>
        <div className={classNames('c-kd-select-geography-container__widgets', theme['c-kd-select-geography-container__widgets'])}>
          {this.renderCheckboxesButton()}
          <TypeSelect
            theme={theme}
            selected={this.state.type}
            onChange={this.changeType}
          />
        </div>
        <div
          className={
            classNames(
              'c-kd-select-geography-container__autocomplete',
              theme['c-kd-select-geography-container__autocomplete'],
            )
          }
        >
          <Autocomplete
            theme={theme}
            setSelectedItems={(item) => {
              onItemAdded(item);
            }}
            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() {
    const { theme } = this.props;
    return (
      <div
        className={
          classNames(
            'c-kd-select-geography-container',
            theme['c-kd-select-geography-container'],
          )
        }
      >
        <h4>Aqui va el select main!</h4>
        {this.renderAutocomplete()}
        {this.renderCheckboxesUnderneath()}
      </div>
    );
  }
}

KdSelectGeography.propTypes = propTypes;
KdSelectGeography.defaultProps = defaultProps;

export default wrap(KdSelectGeography);
