import React from 'react';
import {
  Paper,
  Dialog,
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
  TextField,
  FlatButton,
  Checkbox,
  RaisedButton,
  GridList,
  GridTile,
  Divider
} from 'material-ui';
import {observer, inject} from 'mobx-react';

import './style.scss'
import {LINKS} from "../../routes";
import {Helmet} from "react-helmet";
import {APP_TYPE} from "../../config/app";


@inject('appstate')
@observer
export default class AcceptInvite extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      tokenData: {
        email: ""
      },
      password: "",
      confirm_password: ""
    };
    this.defaultState = Object.assign({}, this.state);
    this.authStore = props.appstate.auth;
    this.http = props.appstate.http;
    this.settingStore = props.appstate.setting;
  }

  handleDialogOpen = (title, message) => {
    this.setState({
      dialogTitle: title,
      dialogMessage: message,
      openDialog: true
    })
  }

  closeDialog = () => {
    this.setState({
      openDialog: false
    })
  }

  handleTextFieldChange = (event, name) => {
    this.setState({
      [name]: event.target.value
    });
  };

  acceptInvite() {
    const {state} = this;
    if (state.password != '' && state.retype != '') {
      let contactData = {
        password: state.password,
        token: this.query.token,
        user_id: state.tokenData.id,
      }

      this.handleDialogOpen('Success', 'Create User Success, Now you can login!');
      this.props.appstate.http.post('authentication/accept_invite_stores', contactData).then(() => {
        this.props.history.push(LINKS.LOGIN);
      })

    //   this.authStore.checkUsernameAvaliability(state.username).then(res => {
    //     if (res) {
    //       this.handleDialogOpen('Success', 'Create User Success, Now you can login!');
    //       this.props.appstate.http.post('authentication/accept_invite', contactData).then(() => {
    //         this.props.history.push(LINKS.LOGIN);
    //       })
    //     }
    //   }
    // )

      // this.handleDialogOpen('Success','Create User Success, Now you can login!');
      // this.props.appstate.http.post('authentication/accept_invite_admin', contactData).then(() => {
      //   vry.push(LINKS.LOGIN);
      // })
    }
    else {
      this.handleDialogOpen('Error', 'Please fill all form!');
    }
  }

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

    if (this.query.token) {
      this.setState({
        tokenData: JSON.parse(atob(this.query.token.split('.')[1]))
      });
    }
  }

  handleRetype = (event) => {
    let password = this.state.password;
    if (password === event.target.value) {
      this.setState({
        error_retype: ''
      })
    }
    else {
      this.setState({
        error_retype: 'Password and retype password is not same'
      })
    }

    this.setState({
      retype: event.target.value
    })
  };

  render() {
    const action = [
      <FlatButton
        label="Ok"
        primary={true}
        onClick={this.closeDialog}
        style={{marginRight: 10}}
      />
    ];

    // const applicationIcon = (this.settingStore.isIconEmpty) ? "/assets/images/bankbtn.png" : this.http.appendImagePath(this.settingStore.setting.icon);
    let applicationIcon =  "http://giift.asacreative.com/giift_logo_wide.4d15de72.png";
    let applicationName = 'Giift';
    if(APP_TYPE === 'btn') {
      applicationIcon = "/assets/images/bankbtn.png";
      applicationName = "BTN";
    }


    return (
      <div className="AcceptInvite">
        <Helmet>
          <meta charSet="utf-8"/>
          <title>{applicationName}</title>
          <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
          <link rel="icon" type="image/png" href={applicationIcon} sizes="96x96"/>
        </Helmet>
        <div style={{width: "100%"}}>
          {
            /*(!this.settingStore.setting.name) ?
              <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo" src="/assets/images/bankbtn.png"/>
                </Paper>
                <h2 style={{
                  color: '#275164',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>BTN</h2>
              </div>
              :
              <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo" src={'/assets/images/bankbtn.png'}/>
                </Paper>
                <h2 style={{
                  color: '#275164',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>{this.settingStore.setting.name}</h2>
              </div>*/
              <div style={{textAlign: "center"}}>
                <Paper style={{
                  backgroundSize: "contain",
                  backgroundClip: "padding-box",
                  padding: 10,
                  height: 75, width: 75,
                  background: '#fff',
                  marginRight: "auto",
                  marginLeft: "auto"
                }} zDepth={1} circle={true}>
                  <img className="logo" src={applicationIcon}/>
                </Paper>
                <h2 style={{
                  color: '#275164',
                  marginRight: "auto",
                  marginLeft: "auto",
                  maxWidth: 500,
                  marginTop: 15,
                  marginBottom: 0
                }}>{applicationName}</h2>
              </div>
          }
        </div>
        <Card style={{width: 350, marginTop: '18px'}} className="cardLite">
          <CardTitle className="align-center" title={<p style={{fontSize: 14}}>New Account Confirmation</p>}>
            <Divider style={{backgroundColor: '#48d8b2', width: '150px'}} className="margin-auto"/>
          </CardTitle>

          <form>
            <CardText>
              <div className="row">
                <p className="label-form">Email</p>
                <TextField
                  hintText="Email"
                  fullWidth={true}
                  name="email"
                  type="email"
                  value={this.state.tokenData.email}
                  disabled={true}
                />
              </div>
              <div className="row">
                <p className="label-form">Password</p>
                <TextField
                  hintText="Password For Login"
                  name="password"
                  fullWidth={true}
                  type="password"
                  value={this.state.password}
                  onChange={(event) => this.handleTextFieldChange(event, 'password')}
                />
              </div>
              <div className="row">
                <p className="label-form">Re-Type Password</p>
                <TextField
                  hintText="Re-Type your Password"
                  name="password"
                  fullWidth={true}
                  type="password"
                  errorText={this.state.error_retype}
                  value={this.state.retype}
                  onChange={this.handleRetype}
                />
              </div>
            </CardText>
            <CardActions>
              <RaisedButton fullWidth={true} primary={true} label="Create your account"
                            onClick={this.acceptInvite.bind(this)}/>
            </CardActions>
          </form>
        </Card>

        <Dialog
          title={this.state.dialogTitle}
          actions={action}
          modal={true}
          contentStyle={{maxWidth: 350}}
          open={this.state.openDialog}
          onRequestClose={() => this.closeDialog()}
        >
          {this.state.dialogMessage}
        </Dialog>
      </div>
    )
  }
}
