import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Modal from 'react-modal'
import Admin from './../admin'
import { fetchEntity, uploadReplay } from '../actions/index'
import '../../app/assets/javascripts/teachable/chat';
import { withExitPrompt } from './util/with-exit-prompt'

const UploadModalStyles = {
  overlay: {
    background: 'rgba(0, 0, 0, 0.50)'
  },
  content: {
    background: 'white',
    fontFamily: 'TeachableSans-Bold',
    fontSize: 14,
    height: 132,
    margin: 'auto',
    maxWidth: 500,
    padding: 20,
    textAlign: 'center'
  }
};

interface WebinarChatProps {
  downloads: any[];
  fetchEntity: any;
  webinar?: any;
  uploadReplay: any;
}

interface DownloadSwitches {}

interface WebinarChatState extends ComponentState {
  clearChatModalOpen?: boolean;
  downloads: any[];
  downloadSwitches?: DownloadSwitches;
  firebaseReference?: any;
  hangoutStatus: string;
  replayVideoStatus: string;
  savedYouTubeID: string;
  showUpgradeButton?: boolean;
  tab: string;
  uploadModalOpen: boolean;
  webinar: any;
  youTubeID: string;
}

class WebinarChat extends React.Component<WebinarChatProps, WebinarChatState> {

  constructor(props) {
    super(props);
    this.state = {
      fetching: true,
      errors: [],
      tab: 'All',
      webinar: {
        chatTimeString: ''
      },
      hangoutStatus: 'Starting',
      downloads: [],
      youTubeID: '',
      savedYouTubeID: '',
      replayVideoStatus: 'unclicked',
      uploadModalOpen: false,
      clearChatModalOpen: false
    };
  }

  componentDidMount() {
    window.Chat.initialize('admin');
    const downloadSwitches = {};
    for (let i = 0; i < 8; i++) {
      downloadSwitches[i] = false;
    }
    $('.match-height-layout').matchHeight();
    let pathDirectories = window.location.pathname.split('/');

    const webinarPromise = this.props.fetchEntity({
      id: pathDirectories[pathDirectories.length - 2],
      directory: 'webinars',
      entityName: 'webinar'
    })
    Promise.all([
      webinarPromise, window.Chat.authPromise
    ]).then(() => {
      this.setState({
        fetching: false,
        webinar: this.props.webinar,
        downloads: this.props.downloads,
        downloadSwitches,
        changesToSave: false,
        firebaseReference: window.firebase.database().ref().child(this.props.webinar.id)
      }, () => {
        this.state.firebaseReference.on('value', this.firebaseUpdate.bind(this), (e) => {
          window.firebase.auth().currentUser.getIdTokenResult().then(t => console.log(t.claims))
          console.log(e)
        });
      });
    });
  }

  checkForChanges() {
    return (this.state.youTubeID !== this.state.savedYouTubeID);
  }

  firebaseUpdate(snap) {
    var value = snap.val();
    window.Chat.updateChatSection(snap.val());
    var downloadSwitches = {
      0: value.controls.downloadSwitches[0],
      1: value.controls.downloadSwitches[1],
      2: value.controls.downloadSwitches[2],
      3: value.controls.downloadSwitches[3],
      4: value.controls.downloadSwitches[4],
      5: value.controls.downloadSwitches[5],
      6: value.controls.downloadSwitches[6],
      7: value.controls.downloadSwitches[7]
    };
    this.setState({
      fetching: false,
      showUpgradeButton: value.controls.showUpgradeButton,
      hangoutStatus: value.controls.hangoutStatus,
      downloadSwitches: downloadSwitches,
      youTubeID: value.controls.youTubeID,
      savedYouTubeID: value.controls.youTubeID,
      replayVideoStatus: value.controls.replayVideoStatus
    });
  }

  changeYouTubeID(e) {
    this.setState({
      youTubeID: e.target.value
    }, () => {
      this.setState({
        changesToSave: this.checkForChanges()
      });
    });
  }

  clickSaveYouTubeID() {
    if (this.state.changesToSave) {
      if (this.state.youTubeID.indexOf("&") > -1) {
        alert('The & symbol is not allowed in the YouTube ID!');
      } else {
        this.state.firebaseReference.child('controls').update({
          "youTubeID": this.state.youTubeID
        });
        this.setState({
          savedYouTubeID: this.state.youTubeID
        }, () => {
          this.setState({
            changesToSave: this.checkForChanges()
          });
        });
      }
    }
  }

  clickStatus(e) {
    var status = e.target.innerHTML;
    var obj = { 'hangoutStatus': status };
    if (status !== 'End') {
      obj["replayVideoStatus"] = 'unclicked';
    }
    this.state.firebaseReference.child('controls').update(obj);
  }

  clickClearChat() {
    this.setState({
      clearChatModalOpen: true
    });
  }

  confirmClearChat() {
    this.state.firebaseReference.child("messages").remove();
    this.state.firebaseReference.child("users").remove();
    window.location.reload();
  }

  changeShowUpgrade(e) {
    this.state.firebaseReference.child('controls').update({
      "showUpgradeButton": e.target.checked
    });
  }

  changeDownloadSwitch(e) {
    this.state.firebaseReference.child('controls').child('downloadSwitches').update({
      [e.target.dataset.index]: e.target.checked
    });
  }

  clickTab(e) {
    var words = e.target.innerHTML.split(' ');
    this.setState({
      tab: words.slice(0, words.length - 1).join(' ')
    }, function() {
      window.Common.scrollOverflowElementToBottom($('.chat-messages:not(.hidden)')[0]);
    });
  }

  clickUploadReplay() {
    if (!this.state.changesToSave && this.state.youTubeID.trim() !== "") {
      this.setState({
        uploadModalOpen: true
      });
    }
  }

  confirmUploadReplay() {
    this.setState({
      uploadModalOpen: false,
      fetching: true
    });
    this.props.uploadReplay({
      webinarId: this.state.webinar.id,
      youTubeID: this.state.youTubeID
    }).then(() => {
      this.setState({
        fetching: false
      });
    });
  }

  closeModal() {
    this.setState({
      uploadModalOpen: false,
      clearChatModalOpen: false
    });
  }

  render() {
    return(
      <div id="webinar-chat">
        { Admin.renderSpinner(this.state.fetching) }
        { Admin.renderGrayedOut(this.state.fetching) }
        <div className="chat-column">
          <ul className="categories">
            <li className={ this.state.tab == "All" ? "selected" : "" } onClick={ this.clickTab.bind(this) }>{ "All (" + $('.chat-messages.all .chat-message').length + ")" }</li>
            <li className={ this.state.tab == "Questions" ? "selected" : "" } onClick={ this.clickTab.bind(this) }>{ "Questions (" + $('.chat-messages.questions .chat-message').length + ")" }</li>
            <li className={ this.state.tab == "General comments" ? "selected" : "" } onClick={ this.clickTab.bind(this) }>{ "General comments (" + $('.chat-messages.comments .chat-message').length + ")" }</li>
            <li className={ this.state.tab == "Hello" ? "selected" : "" } onClick={ this.clickTab.bind(this) }>{ "Hello (" + $('.chat-messages.hello .chat-message').length + ")" }</li>
            <li className={ this.state.tab == "Blocked" ? "selected" : "" } onClick={ this.clickTab.bind(this) }>{ "Blocked (" + $('.chat-messages.blocked .chat-message').length + ")" }</li>
            <div className="clear-chat" onClick={ this.clickClearChat.bind(this) }>Clear Chat</div>
          </ul>
          <div className="chat-messages-padding">
            <div className={ "chat-messages questions" + (this.state.tab == "Questions" ? "" : " hidden") }></div>
            <div className={ "chat-messages comments" + (this.state.tab == "General comments" ? "" : " hidden") }></div>
            <div className={ "chat-messages hello" + (this.state.tab == "Hello" ? "" : " hidden") }></div>
            <div className={ "chat-messages all" + (this.state.tab == "All" ? "" : " hidden") }></div>
            <div className={ "chat-messages blocked" + (this.state.tab == "Blocked" ? "" : " hidden") }></div>
          </div>
          <div className="new-comment">
            <div className="send-button"></div>
            <textarea placeholder="Type comment..."></textarea>
          </div>
        </div>
        <div className="info-column">
          <div className="date-and-time">
            <p>{ this.state.webinar.chatTimeString.split('@')[0] }</p>
            <p>@{ this.state.webinar.chatTimeString.split('@')[1] }</p>
          </div>
          <div className="below-date">
            <h2>{ this.state.webinar.platform === "vimeo" ? "Vimeo" : "YouTube" } video ID</h2>
            <input onChange={ this.changeYouTubeID.bind(this) } value={ this.state.youTubeID || "" } readOnly={ this.state.replayVideoStatus !== 'unclicked' } /><div className={ "save-id-button chat-green-button" + Admin.renderDisabledButtonClass(this.state.fetching || !this.state.changesToSave) + (this.state.replayVideoStatus === 'unclicked' ? '' : ' hidden') } onClick={ this.clickSaveYouTubeID.bind(this) }>Save</div>
            <hr />
            <h2>Hangout status</h2>
            <ul>
              <li className={ this.state.hangoutStatus == 'Starting' ? 'active' : '' } onClick={ this.clickStatus.bind(this) }>Starting</li>
              <li className={ this.state.hangoutStatus == 'Go live' ? 'active' : '' } onClick={ this.clickStatus.bind(this) }>Go live</li>
              <li className={ this.state.hangoutStatus == 'End' ? 'active' : '' } onClick={ this.clickStatus.bind(this) }>End</li>
            </ul>
            <hr />
            { this.renderReplaySection() }
            <div className="toggle clearfix switch-container">
              <h2>
                CTA live&#63;
              </h2>
            	<label>
                <input type="checkbox" onChange={ this.changeShowUpgrade.bind(this) } checked={ this.state.showUpgradeButton || false } />
                <div></div>
            	</label>
            </div>
            <hr />
            { this.state.downloads.map(function(download, index) {
              return(
                <div key={ download.id } className="toggle clearfix switch-container">
                  <h2>
                    { download.name }
                  </h2>
                  <label>
                    <input type="checkbox" onChange={ this.changeDownloadSwitch.bind(this) } checked={ this.state.downloadSwitches[index] || false } data-index={ index } />
                    <div></div>
                  </label>
                </div>
              );
            }.bind(this)) }
          </div>
        </div>
        <Modal isOpen={ this.state.uploadModalOpen } onRequestClose={ this.closeModal.bind(this) } contentLabel="Modal" style={ UploadModalStyles }>
          <div className="upload-confirmation-modal">
            Do you want to upload the replay video now?
            <div className="buttons">
              <div onClick={ this.confirmUploadReplay.bind(this) }>Upload</div>
              <div onClick={ this.closeModal.bind(this) }>Cancel</div>
            </div>
          </div>
        </Modal>
        <Modal isOpen={ this.state.clearChatModalOpen } onRequestClose={ this.closeModal.bind(this) } contentLabel="Modal" style={ UploadModalStyles }>
          <div className="clear-chat-confirmation-modal">
            Are you sure you want to clear the chat?
            <div className="buttons">
              <div onClick={ this.confirmClearChat.bind(this) }>Yes</div>
              <div onClick={ this.closeModal.bind(this) }>Cancel</div>
            </div>
          </div>
        </Modal>
      </div>
    )
  }

  renderReplaySection() {
    var replayText = {
      "unclicked": "The replay has not been uploaded",
      "scheduled": "The replay video upload has been scheduled",
      "uploaded": "The replay video has been uploaded",
      "error": ""
    };
    if (this.state.hangoutStatus === 'End') {
      return(
        <div>
          <h2>Replay video</h2>
          { this.renderReplayUploadButton() }
          <div className={ "upload-time" + (this.state.replayVideoStatus == 'error' ? ' uploadError' : '') }>{ replayText[this.state.replayVideoStatus] }</div>
          <hr />
        </div>
      )
    } else {
      return null;
    }
  }

  renderReplayUploadButton() {
    if (this.state.replayVideoStatus === 'unclicked') {
      return(
        <div>
          Click to upload replay video
          <div className={ "upload-replay-button chat-green-button" + Admin.renderDisabledButtonClass(this.state.fetching || this.state.changesToSave || this.state.youTubeID.trim() === "") } onClick={ this.clickUploadReplay.bind(this) } >Upload replay video</div>
        </div>
      )
    } else if (this.state.replayVideoStatus === 'error') {
      return(
        <div>
          <span style={ { color: 'red' } }>There was an error uploading the video</span>
          <div className={ "upload-replay-button chat-green-button" + Admin.renderDisabledButtonClass(this.state.fetching || this.state.changesToSave || this.state.youTubeID.trim() === "") } onClick={ this.clickUploadReplay.bind(this) } >Try again</div>
        </div>
      )
    } else {
      return null;
    }
  }
}

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

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchEntity, uploadReplay }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(withExitPrompt(WebinarChat));
