import React from 'react';
import { isPopout } from 'utils/popouts';
import map from 'lodash/map';
import { addWatchlist, deleteWatchlist, addTickersToWatchlist} from 'actions/watchlists';
import remove from 'lodash/remove';
import classnames from 'classnames';
import SymbolAutocompleteMulti, {ErrorTypes} from '../../search/SymbolAutocompleteMulti';

const importOperation = 0;
const replaceOperation = 1;
class WatchlistImport extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      operation: importOperation,
      symbols: [],
      errors: [],
    };
  }

  onAddSymbol(sym, index) {
    const sList = this.state.symbols.slice();
    sList.splice(index, 0, sym);
    this.setState({symbols: sList});
  }
  onAddMultiSymbol(syms, index) {
    const sList = this.state.symbols.concat(syms);
    this.setState({symbols: sList});
  }
  onRemoveSymbol(sym, index) {
    const sList = this.state.symbols.slice();
    remove(sList, sym);
    this.setState({symbols: sList});
  }

  onError(errorType, err) {
    switch (errorType) {
    case ErrorTypes.INVALID_SYMBOLS:
      this.setState({errors: err});
      break;
    case ErrorTypes.UNABLE_TO_CONNECT:
      this.setState({errors: null});
      break;
    case ErrorTypes.TOO_MANY_SYMBOLS:
      this.setState({errors: err});
      break;
    default:
      break;
    }
  }

  doImport() {
    const fixLi = this.state.symbols.map((sym) => sym.value);
    if (this.state.operation === importOperation) {
      addTickersToWatchlist(this.props.watchlistId, fixLi);
      bzTrack.track('Watchlist: Import/Edit', {
        name: this.props.watchlistName
      });
    } else if (this.state.operation === replaceOperation) {
      deleteWatchlist(this.props.watchlistId, this.props.widgetId, isPopout());
      addWatchlist(this.props.watchlistName, fixLi, this.props.widgetId, isPopout());
      bzTrack.track('Watchlist: Replace', {
        name: this.props.watchlistName
      });
    }
    this.props.toggle();
    this.setState({symbols: [], errors: [], operation: importOperation});
  }

  backgroundClick(e) {
    if (e.target === this.refs.background) {
      this.closeModal();
    }
  }

  closeModal() {
    this.props.toggle();
    this.setState({symbols: []});
  }

  renderErrors() {
    let errStr = '';
    if (Array.isArray(this.state.errors)) {
      errStr = 'The following symbols were invalid:' + this.state.errors.join(', ');
    } else if (typeof this.state.errors === 'string') {
      errStr = this.state.errors;
    } else {
      errStr = 'Could not connect to the server to verify the symbols you added were valid.';
    }
    return (
      <div>{errStr}</div>
    );
  }

  render() {
    const importWlClasses = classnames('WidgetModal', {'is-hidden': !this.props.show});

    return (
      <div ref="background"
        className={importWlClasses}
        onClick={(e) => this.backgroundClick(e)}>
        <div className="WidgetModal-box">
          <h3 className="WidgetModal-title">Edit Watchlist</h3>
          <div className="WidgetModal-radio">
            <input
              type="radio"
              name="operation"
              id="operation-update"
              defaultChecked
              onClick={() => this.setState({operation: importOperation})}
            />
            <label htmlFor="operation-update"><strong>Update</strong> Add new symbols to this watchlist</label>
          </div>
          <div className="WidgetModal-radio">
            <input
              type="radio"
              name="operation"
              id="operation-replace"
              onClick={() => this.setState({operation: replaceOperation})}
            />
            <label htmlFor="operation-replace"><strong>Replace</strong> Replace this watchlist with a new list</label>
          </div>
          <label className="WidgetModal-label">ADD SYMBOLS</label>
          <div className="WidgetModal-input Search-container">
            <SymbolAutocompleteMulti
              dynamicSizing
              multiPlaceholder={this.state.symbols.length === 0 ? 'Search, paste, or drag a list of symbols' : 'Search...'}
              symbols={this.state.symbols}
              onAddSymbol={(data, index) => this.onAddSymbol(data, index)}
              onAddMultiSymbol={(data, index) => this.onAddMultiSymbol(data, index)}
              onRemoveSymbol={(data, index) => this.onRemoveSymbol(data, index)}
              onError={(errType, errors) => this.onError(errType, errors)}
            />
          </div>
          {this.state.errors && this.state.errors.length !== 0 && this.renderErrors()}
          <div className="WidgetModal-proceed">
            <button className="Button Button--text" onClick={() => this.closeModal()}>Cancel</button>
            <button className="Button Button--blue" onClick={() => this.doImport()}>Submit</button>
          </div>
        </div>
      </div>
    );
  }
}

WatchlistImport.propTypes = {
  watchlistId: React.PropTypes.string,
  watchlistName: React.PropTypes.string,
  widgetId: React.PropTypes.number,
  toggle: React.PropTypes.func,
  show: React.PropTypes.bool
};

export default WatchlistImport;
