import React from 'react';
import { dispatchCustomEvent } from '../../utils';
import { ASC, SHOW_AUTOCOMPLETE, HIDE_AUTOCOMPLETE, SELECT, ANY, CUSTOM_OPTION, SELECT_OPTION } from '../../constants';


export const KdSelect = React.createClass({
  getInitialState() {
    return {
      optionsCustom: this.props.mainSelector.optionValues.customOptions || [],
    }
  },
  fetchItemInfo(value){
    const { kdFilterModel, api, events, setSelectedItems } = this.props;
    if (value.length && kdFilterModel) {
      const onRequestDone = (data) => {
        const item = data.KdResult.Result[0];
        setSelectedItems({ label: item.KdLabel, value: item.KdId, ...item });
      };
      let request = kd.Request(kdFilterModel.getEntityType(), 'Search');
      request.setUrlBase(api.url);
      request.setApiKey(api.key);
      request.setAjaxDone(onRequestDone);
      request.setQ(value);
      request.requestData();
    }
  },
  handleChange(e){
    const action = e.target.selectedOptions[0].getAttribute('data-action');
    const {
      setSelectedItems,
      setAutocompleteVisibility,
      resetSelected
    } = this.props;

    switch (action) {
      case CUSTOM_OPTION:
        const label = e.target.selectedOptions[0].getAttribute('data-label');
        if (label) {
          this.fetchItemInfo(label);
          setAutocompleteVisibility(false);
        }
        break;
      case SHOW_AUTOCOMPLETE:
        setAutocompleteVisibility(true);
        break;
      case HIDE_AUTOCOMPLETE:
        setAutocompleteVisibility(false);
        resetSelected();
        break;
      default:
        break;
    }
  },
  renderAnyOption() {
    const { mainSelector, entityType } = this.props;
    const anyLabel = mainSelector.optionValues.anyOption.label || `${ANY} ${entityType}`;
    return (
      <option
        key={ ANY }
        data-action={ HIDE_AUTOCOMPLETE }
        value={ ANY }>
        {anyLabel}
      </option>
    );
  },
  renderSelectOption() {
    const { mainSelector, entityType } = this.props;
    const selectLabel = mainSelector.optionValues.selectOption.label || 'Select...';
    return (
      <option
        key={ SELECT_OPTION }
        data-action={ HIDE_AUTOCOMPLETE }
        value={ SELECT_OPTION } >
        { selectLabel }
      </option>
    );
  },
  renderUserSpecifiedOption(){
    const { mainSelector, entityType } = this.props;
    return (
      <option
        key={ SHOW_AUTOCOMPLETE }
        data-action={ SHOW_AUTOCOMPLETE }
        value={ SHOW_AUTOCOMPLETE } >
          { mainSelector.optionValues.userSpecifiedOption.label || `Search ${entityType}(s)...`}
      </option>
    );
  },
  renderCustomOptions() {
    return (
      this.state.optionsCustom.map(
        (item) => (
          <option key={ item.value }
                  data-action={ CUSTOM_OPTION }
                  data-label={ item.label }
                  data-value={ item.value }
                  value={ item.value } >
            { item.label }
          </option>
        )
      )
    );
  },
  renderOptions(){
    let options = [];
    const { mainSelector } = this.props;

    if (mainSelector.optionValues.selectOption.visible) {
      options.push(this.renderSelectOption());
    }
    if (mainSelector.optionValues.anyOption.visible) {
      options.push(this.renderAnyOption());
    }
    options.push(this.renderCustomOptions);
    if (mainSelector.optionValues.userSpecifiedOption.visible !== false) {
      options.push(this.renderUserSpecifiedOption());
    }
    return options;
  },

  defaultValue(){
    const { mainSelector, selectedItems, isChickletNone } = this.props;
    if (mainSelector.optionValues.selectOption.visible) {
      return SELECT_OPTION;
    }

    if (!mainSelector.optionValues.anyOption.visible && isChickletNone) {
      if (selectedItems.length) {
        return selectedItems[0].value;
      }
    }
    return ANY;
  },

  render() {
    const { mainSelector } = this.props;
    return (
      <div className='c-kd-select'>
        <select
          key={ mainSelector.selected }
          defaultValue={ mainSelector.selected || this.defaultValue() }
          onChange={this.handleChange} >
          {this.renderOptions()}
        </select>
      </div>
    );
  }
});