import extend from 'extend';
import React, { PropTypes } from 'react';

import ClearAll from '../ClearAll';
import wrap from '../ItemContainerWrapper';
import { buildCustomOptions, buildCustomOption, buildChickletValue } from './options';
import { ANY, CHICKLET_NONE } from '../../constants';

const defaultProps = {
  emptyItems: true,
  mainSelector: {
    optionValues: {
      anyOption: {
        visible: true,
      },
      customOptions: [],
    },
  },
  events: {},
};

const propTypes = {
  emptyItems: PropTypes.bool,
  onOptionSelected: PropTypes.func,
  onItemAdded: PropTypes.func,
  onClearChicklets: PropTypes.func,
  onSelectionHandler: PropTypes.func,
  onSetChicklets: PropTypes.func,
  kdFilterModel: PropTypes.object,

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

  events: PropTypes.shape({
    onChange: PropTypes.func,
    onSelect: PropTypes.func,
  }),

  selectedValuesInitial: PropTypes.array,
};

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

    this.mainSelector = extend(true, {}, defaultProps.mainSelector, this.props.mainSelector);

    const { optionValues } = this.mainSelector;
    this.mainSelectorOptionsCustom = buildCustomOptions(optionValues);

    this.defaultOption = this.mainSelectorOptionsCustom[0];
    this.state = {
      selectedOption: this.defaultOption,
    };

    this.onSelectChange = this.onSelectChange.bind(this);
    this.onClearChicklets = this.onClearChicklets.bind(this);
  }

  componentWillMount() {
    const selected = this.props.selectedValuesInitial;
    if (selected && selected.length) {
      const customInitialOptions = selected.map(buildCustomOption);
      const selectedChicklets = customInitialOptions.map(
        option => buildChickletValue(option, this.props.kdFilterModel),
      );

      this.props.onSetChicklets(selectedChicklets);
      const selectedOption = [...customInitialOptions].pop();

      this.setState({
        selectedOption,
      }, () => this.props.onOptionSelected(selectedOption.id));
    } else {
      this.props.onOptionSelected(this.state.selectedOption.id);
    }
  }

  componentWillReceiveProps(nextProps) {
    const { emptyItems } = nextProps;

    if (emptyItems && this.props.emptyItems !== emptyItems) {
      this.onClearChicklets();
    }
  }

  onSelectChange({ target }) {
    const selectedOption = this.mainSelectorOptionsCustom.find(
      option => option.id === target.value,
    );

    if (selectedOption.id === ANY) {
      this.props.onClearChicklets();
    } else {
      this.props.onItemAdded(buildChickletValue(selectedOption, this.props.kdFilterModel));
    }

    this.setState({
      selectedOption,
    }, () => {
      this.props.onOptionSelected(selectedOption.id);
      const event = {
        label: selectedOption.displayName,
        value: selectedOption.id,
        direction: selectedOption.direction,
      };

      const { events: { onChange, onSelect } } = this.props;
      if (onChange) {
        onChange(event);
      }
      if (onSelect) {
        onSelect(event);
      }
    });
  }

  onClearChicklets() {
    this.setState({
      selectedOption: this.defaultOption,
    }, () => this.props.onOptionSelected(this.defaultOption.id));
    this.props.onClearChicklets();
  }

  render() {
    return (
      <div className="infront ofd-select-sort-order">
        <div className="c-base-select">
          <select onChange={this.onSelectChange} value={this.state.selectedOption.id}>
            {
              this.mainSelectorOptionsCustom.map(option =>
                (
                  <option value={option.id} key={option.id}>{option.displayName}</option>
                ),
              )
            }
          </select>
        </div>
        {
          !this.props.emptyItems &&
            this.props.widgetEventOnSelectAction !== CHICKLET_NONE &&
            <ClearAll onClick={this.onClearChicklets} />
        }
      </div>
    );
  }
}

KdSelectSortOrder.propTypes = propTypes;
KdSelectSortOrder.defaultProps = defaultProps;

export default wrap(KdSelectSortOrder);
