import React, { Component } from 'react';
import PropTypes from 'prop-types';
import GRecaptcha from '../GRecaptcha.jsx';
import SpinningGear from './SpinningGear';
import InternalServerError from './InternalServerError';
import ManualEmailValidation from './ManualEmailValidation';
import FooterComponent from './FooterComponent';

import '../styles/css/bootstrap.css';
import '../styles/css/splunk-core-v3.1.css';
import '../styles/css/splunk-form.css';
import '../styles/css/splunk-signup-component.css';
/*eslint no-console: ['error', { allow: ['info','warn', 'error', 'log'] }] */

import SplunkInput from '../SplunkInput.jsx';
const BTN_CLS_NAME = 'splunk-btn-login sp-btn-default btn-medium btn-block';
const BTN_DISABLED_CLS_NAME = BTN_CLS_NAME + ' disabled';

export default class LoginComponent extends Component {

  constructor(props) {
    super(props);
    let {config} = props;
    this.serverURL = config.server.url;
    this.login = this.login.bind(this);
    this.notificationCallback = this.notificationCallback.bind(this);
    this.onloadCallback = this.onloadCallback.bind(this);
    this.verifyCallback = this.verifyCallback.bind(this);
    this.allInputs = [];
    this.state = {
      'btnCls': BTN_DISABLED_CLS_NAME,
      'isValid': false,
      links: {
        lostPasswordUri: config.links.lostPassword,
        lostUsernameUri: config.links.lostUsername,
        createAccount: config.links.createAccount,
        partnerPortal: config.links.partnerPortal
      },
      recaptcha: config.recaptcha,
      showSpinner: false,
      serverError: false,
      emailValidation: false
    }
  }

  componentDidMount() {
    fetch(this.serverURL + "/csrfToken")
      .then(res => res.json())
      .then(
        (result) => {
          console.info (result);
          this.setState({
            _csrf: result._csrf
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
      // this.recaptchaInstance.render('recaptcha-login-element');
  }


  static propTypes = {
    config: PropTypes.object  
  };
  
  checkSession (callback) {
    this.oktaAuth.session.exists().then(callback);
  }

  notificationCallback() {
    if (this.username.isValid() && this.password.isValid()) {
      this.setState({
        'btnCls': BTN_CLS_NAME,
        'isValid': true
      });
    }
    else {
      this.errorDiv.innerHTML = '';
      this.setState({
        'btnCls': BTN_DISABLED_CLS_NAME,
        'isValid': false
      });
    }
  }

  login (e) {
    if (!this.state.isValid) return;
    e.preventDefault();
    this.setState({
      showSpinner: true
    });
    fetch(this.serverURL + "/api/v2/auth/login", {
      method: 'post',
      body: JSON.stringify({
        username: this.username.value,
        password: this.password.value
      })
    })
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          showSpinner: false
        });
        if (result.status === 'error') {
          this.errorDiv.innerHTML = 'Please check your username and password and try again.'
        }
        else if (result.status === 'success'){
          console.info(result)
        }
      },
      (error) => {
        this.setState({
          serverError: true,
          showSpinner: false
        });
      }
    )
  }

  validate(value, callback) {
    setTimeout(function() {
      if (value === 'error')
        callback('Validation Failed')
      else
        callback(true);
    }, 300);
  }

  onContextMenu() {
    return false;
  }

  verifyCallback() {
    console.warn ('verify', this.recaptchaInstance);
  }

  onloadCallback() {
    console.warn ('onload', this.recaptchaInstance);
  }

  renderServerError() {
    if (this.state.serverError) {
      return <InternalServerError />
    }
  }

  renderSpinner() {
    if (this.state.showSpinner) {
      return <SpinningGear />
    }
  }

  renderEmailValidation() {
    if (this.state.emailValidation) {
      return <ManualEmailValidation />
    }
  }

  renderRecaptcha() {
    if (this.state.recaptcha.enabled) {
      return <GRecaptcha
        sitekey={this.state.recaptcha.siteKey}
        render='explicit'
        ref={e => this.recaptchaInstance = e}
        verifyCallback={this.verifyCallback}
        onloadCallback={this.onloadCallback}
      />
    }
  }

  render() {
    return (
      <div id='themeSelect' style={{display: 'block'}} className='dark-theme-form-container inverted'>
        <div id="spinnerContainer">
          {this.renderServerError()}
          {this.renderSpinner()}
          {this.renderEmailValidation()}
        </div>
        <div id='contentSection' style={{visibility: 'visible'}}>
          <div id='login-form' className='splunk_login'>
            <h4 id='titleHead' className='splunk2-h4 globalize' data-locale-key='LOG_IN'>Log In</h4>
            <div id='loginError' ref={divEle => {this.errorDiv = divEle}}/>
            <div className='splunk-form'>
              <SplunkInput title='Username' dataLocaleKey='USERNAME' validate={this.validate} notifier={this.notificationCallback} ref={input => {this.username = input}} />
              <SplunkInput title='Password' dataLocaleKey='PASSWORD' inputType='password' validate={this.validate} notifier={this.notificationCallback} ref={input => {this.password = input}} />
              <div id='re-captcha-login' style={{display: 'none'}} className='re-captcha'>
                <div id='recaptcha-login-element' tabIndex={3} />
              </div>
              <div className='splunk-submit'>
                <button type='submit' id='login-submit' tabIndex={4} className={this.state.btnCls} onClick={this.login}>
                  <span className='globalize' data-locale-key='LOG_IN'>Log In</span>
                </button>
              </div>
              <br />
              {this.renderRecaptcha()}
              <FooterComponent urls={this.state.links} onContextMenu={this.onContextMenu} />
            </div>
          </div>
        </div>
      </div>
    );
  }
}