import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Modal from 'react-modal'
import orderBy from 'lodash/orderBy';
import truncate from 'lodash/truncate';
import Admin from './../admin'
import { fetchEntities } from '../actions/index'
import NewEntity from './new-entity'

const ModalStyles = {
  overlay: {
    background: 'rgba(0, 0, 0, 0.50)'
  },
  content: {
    background: 'white',
    padding: 0,
    margin: 'auto',
    maxWidth: 1000,
    height: 359
  }
};

interface WebinarsIndexProps {
  fetchEntities: any;
  timeframe: string;
  webinarTimes: any[];
}

interface WebinarsIndexState extends ComponentState {
  modalOpen: boolean;
  tab: string;
  webinars: any[];
}

class WebinarsIndex extends React.Component<WebinarsIndexProps, WebinarsIndexState> {

  constructor(props) {
    super(props);
    this.state = {
      fetching: true,
      webinars: [],
      modalOpen: false,
      searchText: '',
      searchProperty: 'time_parsed',
      tab: 'Upcoming Live'
    };
  }

  componentDidMount() {
    this.props.fetchEntities('webinars').then(() => {
      this.setState({
        fetching: false,
        webinars: this.props.webinarTimes
      });
    });
  }

  clickNew() {
    this.setState({
      modalOpen: true
    });
  }

  closeModal() {
    this.setState({
      modalOpen: false
    });
  }

  filterByTime(webinar) {
    var duration = (90 * 60 * 1000);
    switch (this.state.tab) {
      case 'Upcoming Live':
        return webinar.webinar_type === 'live' && ((webinar.timestamp * 1000) + duration) > Date.now();
        break;
      case 'Past Live':
        return webinar.webinar_type === 'live' && ((webinar.timestamp * 1000) + duration) < Date.now();
        break;
      case 'Automated':
        return webinar.webinar_type === 'automated';
        break;
      default:
        return null;
    }
  }

  sortByTimestamp(webinar) {
    return webinar.timestamp;
  }

  render() {
    const { webinars, searchText, searchProperty } = this.state;
    var filteredWebinars = Admin.filterSearchText(webinars.filter(this.filterByTime.bind(this)), searchText, searchProperty);
    return(
      <div id="webinars-index" className="component">
        <div className="clearfix">
          <h1 className="search-box-header">Webinars</h1>
          { Admin.renderTopTabs.call(this, 'webinars', ["Upcoming Live", "Past Live", "Automated"]) }
          <a className={ "orange-button float-button btn" + Admin.renderDisabledButtonClass(this.state.fetching) } onClick={ this.clickNew.bind(this) }>Add Webinar</a>
          <input className="search-box margin" onChange={ Admin.changeSearchText.bind(this) } value={ this.state.searchText } />
        </div>
        <div className="white-box">
          { Admin.renderSpinner(this.state.fetching) }
          { Admin.renderGrayedOut(this.state.fetching) }
          <table className='admin-table contains-links'>
            <thead>
              <tr>
                <th><div className={ Admin.sortClass.bind(this)("time_parsed") } onClick={ Admin.clickHeader.bind(this, "time_parsed") }>Time</div></th>
                <th><div className={ Admin.sortClass.bind(this)("name") } onClick={ Admin.clickHeader.bind(this, "name") }>Name</div></th>
                <th><div className={ Admin.sortClass.bind(this)("title") } onClick={ Admin.clickHeader.bind(this, "title") }>Title</div></th>
                <th>Registrants</th>
                <th>Chat</th>
                <th>Pages</th>
              </tr>
            </thead>
            <tbody>
              <tr><td></td><td></td><td></td><td></td><td></td></tr>
              { orderBy(filteredWebinars, [this.state.searchProperty == 'time_parsed' ? this.sortByTimestamp.bind(this) : Admin.commonSort.bind(this)], [(this.state.searchProperty === 'time_parsed' && this.state.tab === 'Past Live') ? 'desc' : 'asc']).map((webinar, index) => {
                return(
                  <tr key={ index } data-id={ webinar.id }>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}` }>
                        { webinar.time_parsed }
                      </a>
                    </td>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}` }>
                        { truncate(webinar.name, { length: 53 }) }
                      </a>
                    </td>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}` }>
                        { truncate(webinar.title, { length: 43 }) }
                      </a>
                    </td>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}` }>
                        { webinar.registrations }
                      </a>
                    </td>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}/chat` }>
                        <img className="chat-bubble" src={ window.Images.chatBubble } />
                      </a>
                    </td>
                    <td>
                      <a href={ `/admin/webinars/${webinar.id}` }>
                        <img src={ window.Images.threeDots } />
                      </a>
                      <ul className="page-links-inner-menu">
                        <div></div>
                        <li><a href={ "/webinars/" + webinar.url + "/register" } target="_blank" rel="noopener noreferrer">Register</a></li>
                        <li><a href={ "/webinars/" + webinar.url + "/thank-you" } target="_blank" rel="noopener noreferrer">Thank You</a></li>
                        <li><a href={ "/webinars/" + webinar.url + "/play" } target="_blank" rel="noopener noreferrer">Play</a></li>
                        <li><a href={ "/webinars/" + webinar.url + "/replay" } target="_blank" rel="noopener noreferrer">Replay</a></li>
                      </ul>
                    </td>
                  </tr>
                );
              }) }
            </tbody>
          </table>
        </div>
        <Modal isOpen={ this.state.modalOpen } onRequestClose={ this.closeModal.bind(this) } contentLabel="Modal" style={ ModalStyles }>
          <NewEntity entityName="webinar" initialEntity={ { name: "", title: "", url: "", time: "", time2: "" } } redirect={ true } />
        </Modal>
      </div>
    );
  }

  componentDidUpdate() {
    $('.match-height-layout').matchHeight();
  }
}

const mapStateToProps = (reducers, props) => {
  return reducers.standardReducer;
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchEntities }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(WebinarsIndex);
