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

import ClearAll from '../ClearAll';

import wrap from '../ItemContainerWrapper';
import { buildCustomOptions, buildCustomOption, buildChickletValue } from './options';
import { fireEvents } from '../../utils';
import { ANY, SELECT_OPTION, ADD_CHICKLET } from '../../constants';

const defaultProps = {
  emptyItems: true,
  selectBehavior: ADD_CHICKLET,
  mainSelector: {
    optionValues: {
      anyOption: {
        visible: true,
      },
      selectOption: {
        visible: true,
      },
      customOptions: [],
      userSpecifiedOption: {
        visible: true,
      },
    },
  },
  events: {},
  clearAll: { visible: true },
  chicklets: {
    clearAll: { visible: true },

  },
};

const propTypes = {
  theme: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.func,
  ]).isRequired,
  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);
    this.chicklets = extend(true, {}, defaultProps.chicklets, this.props.chicklets, { sortable: true });

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

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

  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);
      if (this.props.isChickletNone) {
        const selectedOption = [...customInitialOptions].pop();
        this.setState({
          selectedOption,
        },
          () => this.props.onOptionSelected(selectedOption.id)
        );
      }
    } else {
      this.props.onOptionSelected(this.state.selectedOption.id);
    }
  }

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

    if (selectedOption.id === ANY) {
      this.props.onClearChicklets();
    } else if (selectedOption.id !== SELECT_OPTION) {
      this.props.onItemAdded(buildChickletValue(selectedOption, this.props.kdFilterModel));
      if (!this.props.isChickletNone) {
        selectedOption = this.mainSelectorOptionsCustom.find(
          option => option.id === SELECT_OPTION,
        ) || selectedOption;
      }
    }
    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;
      fireEvents([onChange, onSelect], event);
    });
  }

  render() {
    const { theme } = this.props;
    return (
      <div
        className={
          classNames(
            'infront',
            'ofd-select-sort-order',
            theme.infront,
            theme['ofd-select-sort-order'],
          )
        }
      >
        <div className={classNames('c-base-select', theme['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.isChickletNone &&
              this.chicklets.clearAll.visible &&
              <ClearAll theme={theme} onClick={this.props.onClearChicklets} />
        }
      </div>
    );
  }
}

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

export default wrap(KdSelectSortOrder);
