import React from 'react';
import {observer, inject} from 'mobx-react';
import {
  Form,
  Input,
  Button,
  Select,
  DatePicker,
  Icon,
  message,
  Spin
} from 'antd'
import InviteForm from './form';
import css from 'reactcss';
import {LINKS} from './../../routes';
import './style.scss';

const {Option, OptGroup} = Select;
const FormItem = Form.Item;

@inject('appstate')
@observer
export default class InviteConfirmationComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      isLoading: false
    };
    this.defaultState = Object.assign({}, this.state);
    this.style = css({
      default: {
        container: {
          minHeight: '100vh'
        },
        loginForm: {
          paddingTop: '15%'
        }
      }
    })
    this.authStore = props.appstate.auth;
  }

  componentDidMount() {
    console.log('InviteConfirmationComponent loaded!');
    this.query = this
      .props
      .location
      .search
      .substr(1)
      .split('&')
      .reduce((q, value) => {
        const [k,
          v] = value.split('=');
        q[k] = v;
        return q;
      }, {});
  }

  confirm() {
    let message = message;
    this.setState({isLoading: true})
    this
      .formInstance
      .validateFields((err, fields) => {
        if (err) {
          return console.error(err)
        }

        setTimeout(() => {
          this
            .authStore
            .acceptInvite(this.query.token, fields.password)
            .then(res => {
              // message.success(res.message);
              this
                .props
                .history
                .push(LINKS.LOGIN);
            })
            .catch(err => {
              console.log(err);
              message.error(err.message);
              this.setState({isLoading: false})
            });
        }, 1000);
      })
  }

  render() {

    return (
      <div className="login" style={this.style.container}>
        <div className="login-box">
          <Spin spinning={this.state.isLoading}>
            <div className="header">
              <div>
                <img alt="logo" src="/assets/images/green.png"/>
              </div>
              <p>Accelerate</p>
            </div>
            <div style={{
              textAlign: "center"
            }}>
              <InviteForm ref={form => this.formInstance = form}/>
              <Button
                style={{
                width: "100%",
                marginBottom: 10
              }}
                type="primary"
                size="large"
                onClick={e => this.confirm()}>Confirm</Button>
            </div>
          </Spin>
        </div>
      </div>
    )
  }
}
