import React from 'react';
import classnames from 'classnames';
import { connect } from 'react-redux';
import {userService} from '../../../services';
import DropdownMenu from 'components/ui/inputs/DropdownMenu';
import ToggleSwitch from 'components/ui/inputs/ToggleSwitch';
import {
  toggleAlert,
  toggleAlerts,
  changeSound,
  changeSounds
} from 'actions/watchlists';
import map from 'lodash/map';
import sortBy from 'lodash/sortBy';

class Alerts extends React.Component {
  constructor() {
    super();
    this.state = {
      activeTab: 'channels',
      channelList: {},
      selectedWatchlist: null
    };
    this.getChannels();
  }

  getAllSame(collection, getValue = (c, k) => c[k]) {
    let value;
    for (const key in collection) {
      const val = getValue(collection, key);

      if (value === undefined) {
        value = val;
        continue;
      }

      if (value !== val) {
        return undefined;
      }
    }
    return value;
  }

  getChannels() {
    userService.getAlertChannels().then((data) => {
      this.setState({channelList: data});
    });
  }

  toggleChannel(channelId) {
    if (this.state.channelList[channelId]) {
      if (this.state.channelList[channelId].subscription_type) {
        userService.deleteAlertChannel(channelId).then(() => this.getChannels());
      } else {
        userService.updateAlertChannel(channelId, 'realtime').then((data) => this.setState({channelList: data}));
      }
    }
  }

  switchTab(tab) {
    this.setState({activeTab: tab});
  }

  selectWatchlist(watchlistId) {
    this.setState({selectedWatchlist: watchlistId});
  }

  renderTab() {
    if (this.state.activeTab === 'channels') {
      return (
        <section className="preferences-alerts">
          <p className="preferences-alerts-description">
            Channel based alerts will email you whenever a new story is posted under that channel.
          </p>
          <ul className="alerts-channels">
            {map(sortBy(this.state.channelList, (c) => c.channel_name), (channel) =>
              <li className={classnames({active: channel.subscription_type})} key={channel.channel_id}
                  onClick={() => this.toggleChannel(channel.channel_id)}>
                <label>{channel.channel_name}</label>
              </li>
            )}
          </ul>
        </section>
      );
    }
    const watchlists = {};
    this.props.watchlists.forEach((v, k) => {
      watchlists[k] = v.get('name');
    });
    let tickers = [];
    if (this.state.selectedWatchlist !== null) {
      tickers = this.props.watchlists.getIn([this.state.selectedWatchlist, 'tickers']).toJS();
    }
    const sounds = {
      '': 'None',
      alarm: 'Alarm',
      droplet: 'Droplet',
      glass: 'Glass',
      morsecode: 'Morsecode',
      opencan: 'Opencan',
      pot: 'Pot',
      shatter: 'Shatter',
      siren: 'Siren'
    };
    const allTickerValue = this.getAllSame(tickers, (c, k) => c[k].emailAlertsEnabled);
    let allSoundValue = this.getAllSame(tickers, (c, k) => c[k].sound);
    if (allSoundValue === undefined) {
      allSoundValue = null;
    }
    return (
      <section className="preferences-alerts">
        <p className="preferences-alerts-description">
          Watchlist based alerts will email you whenever a story is posted for the chosen ticker.
        </p>
        <div className="alerts-watchlist-header">
          <DropdownMenu items={watchlists} value={this.state.selectedWatchlist} onChange={(id) => this.selectWatchlist(id)} defaultText="Select a watchlist..." />
        </div>
        <div className="alerts-watchlist-tickers">
          <div className="alerts-watchlist-ticker">
            <div className="alerts-watchlist-ticker__symbol"><label>Alert</label></div>
            <div className="alerts-watchlist-ticker__toggle"><label>Realtime Email</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label>Sound Alert</label></div>
          </div>
          <div className="alerts-watchlist-ticker">
            <div className="alerts-watchlist-ticker__symbol"></div>
            <div className="alerts-watchlist-ticker__toggle">
              {
                this.state.selectedWatchlist !== null && (
                  <span>
                    <ToggleSwitch
                      value={!!allTickerValue}
                      onToggle={() => toggleAlerts(tickers.map(t => t.id), this.state.selectedWatchlist, !allTickerValue)}
                    />
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <DropdownMenu
                      items={sounds}
                      value={allSoundValue}
                      onChange={(newsound) => changeSounds(tickers.map(t => t.id), newsound)}
                      defaultText="None"
                    />
                  </span>
                )
              }
            </div>
          </div>
          {map(tickers, (t) =>
            <div className="alerts-watchlist-ticker" key={t.id}>
              <div className="alerts-watchlist-ticker__symbol">{t.symbol}</div>
              <div className="alerts-watchlist-ticker__toggle">
                <ToggleSwitch value={t.emailAlertsEnabled ? true : false} onToggle={() => toggleAlert(t.id, this.state.selectedWatchlist, !t.emailAlertsEnabled)} />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <DropdownMenu items={sounds} value={t.sound || null} onChange={(newsound) => changeSound(t.id, newsound)} defaultText="None" />
              </div>
            </div>
          )}
        </div>
      </section>
    );
  }

  render() {
    return (
      <div className="preferences-page">
        <ul className="preferences-tabs">
          <li className={classnames('preferences-tab', {active: this.state.activeTab === 'channels'})} onClick={() => this.switchTab('channels')}>
            Channels
          </li>
          <li className={classnames('preferences-tab', {active: this.state.activeTab === 'watchlists'})} onClick={() => this.switchTab('watchlists')}>
            Watchlists
          </li>
        </ul>
        {this.renderTab()}
      </div>
    );
  }
}

Alerts.propTypes = {
  watchlists: React.PropTypes.object
};

function selectWatchlists(state) {
  return {
    watchlists: state.watchlists.watchlists
  };
}

export default connect(selectWatchlists)(Alerts);
