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 LoadingDialog from '../LoadingDialog/index';
import {LINKS} from "../../routes";


@inject('appstate')
@observer
export default class ChangePassword extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
     password : '',
     error_retype : '',
     retype : '',
     loading : false,
     tokenData : {
      email : ""
     },
     status : 0,
     openDialog : false
    };
    this.defaultState = Object.assign({}, this.state);
    this.authStore = props.appstate.auth;
    this.http = props.appstate.http;
  }


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

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

  acceptInvite() {
    const {state} = this;
    if(state.username != '' && state.password != '' && state.retype != ''){
      this.setState({loading : true})
      let contactData = {
        password : state.password,
        id : state.tokenData.id,
      }
      this.handleDialogOpen('Success','Change Password Success');
      this.http.post('authentication/reset_password',contactData).then(res=>{
        this.setState({loading : false,status : 1});
        this.handleDialogOpen('Success','Success change password');
      }).catch(err=>{
        this.setState({loading : false,status : 0});
        this.handleDialogOpen('Error','Something went wrong');
      })
      // this.props.appstate.http.post('authentication/accept_invite_admin', contactData).then(() => {
      // })
    }
    else{
      this.handleDialogOpen('Error','Please fill all form!');
    }
  }



  componentDidMount() {
    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
    })
  };

  closeDialog = ()=>{
    if(this.state.status){
      this.props.history.push(LINKS.LOGIN);
    }
    else{
      this.setState({
        openDialog : false
      })
    }
  }

  render() {

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

    return (
      <div className="AcceptInvite">
        <img className="logo" src="http://giift.asacreative.com/giift_logo_wide.4d15de72.png" style={{maxWidth : '200px'}}/>
        <h1 style={{color:'#275164'}}>5 Roti dan 2 Ikan</h1>
        <h4 style={{color:'#55dab6'}}>Giift</h4>
        <Card style={{width:450, marginTop:'18px'}} className="cardLite">
          <CardTitle className="align-center" title={<p style={{fontSize:14}}>Confirm Password</p>}>
            <Divider style={{backgroundColor:'#48d8b2', width:'150px'}} className="margin-auto"/>
          </CardTitle>

          <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"
              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="Change password" onClick={() => this.acceptInvite()}/>
          </CardActions>
        </Card>

        <Dialog
          title={this.state.dialogTitle}
          actions={action}
          modal={true}
          contentStyle={{maxWidth: 350}}
          open={this.state.openDialog}
          onRequestClose={() => this.setState({openDialog : false})}
        >
          {this.state.dialogMessage}
        </Dialog>
        <Dialog
          open={this.state.loading}
          contentStyle={{maxWidth: 350}}
          modal={true}
        >
        <div style={{textAlign: 'center'}}>
          <LoadingDialog/>
        </div>
        </Dialog>
      </div>
    )
  }
}
