import React from 'react';
import {inject, observer} from 'mobx-react';
import {Form, Icon, message, Select} from 'antd'
import bind from 'bind-decorator';
import {
  Card,
  CardText,
  CardTitle,
  Divider,
  RaisedButton,
  TextField,
  Toolbar,
  ToolbarGroup,
  ToolbarTitle,
} from 'material-ui';
import ModeEdit from 'material-ui/svg-icons/editor/mode-edit';
import './style.scss';
import get from 'lodash.get';
const {Option, OptGroup} = Select;
const FormItem = Form.Item;

// import * as _ from 'lodash';

@inject('appstate')
@observer
class Password extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.bankStore = props.appstate.bank;
    this.state = {
      currency: '',
      previewVisible: false,
      previewImage: '',
      fileList: [{
        uid: -1,
        name: 'xxx.png',
        status: 'done',
        url: 'http://lorempixel.com/400/400/abstract/',
      }],
      uploadedFile: [],
      uploading: false,
      openedDialogBank : false,
      openedDialog: false,
      openedEditDialog: false,
      openedDialogProfile:false,
      openedDialogPhoto:false,
      disabled: false,
      password : '',
      retype : '',
      old_password : '',
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.currency = props.appstate.currencyStore;
    this.appstate = props.appstate;
  }

  componentDidMount() {
    // this.bankStore.getByUserID('tesss');
    // this.currency.getAll();
  }

  handleEditPassword = () => this.setState({disabled: false});

  handleSavePassword = () => {
    if(this.state.password == '' || this.state.retype == '' || this.state.old_password == ''){
      this.globalUI.openSnackbar('Please fill all form');
      return;
    }

    if(this.state.error_retype != ''){
      this.globalUI.openSnackbar("Retype password didn't match the password");
      return;
    }

    this.globalUI.openLoading();
    this.authStore.changePassword({
      password : this.state.password,
      old_password : this.state.old_password
    }).then(res=>{
      this.globalUI.closeLoading();
      this.setState({
        disabled : true,
        password : '',
        old_password : '',
        retype : ''
      });
      this.globalUI.openSnackbar('Success change password');
    }).catch(err=>{
      console.log(err,'Errornya');
      this.globalUI.closeLoading();
      this.globalUI.openSnackbar('Error : '+err.message);
    })
  };

  saveProfile() {
    const {form} = this.props;

    form.validateFields((err, fields) => {

      if (err) {
        return console.error(err);
      }

      this.authStore.updateProfile(fields)
        .then(res => {
          message.success('Profile Updated!');
        })
        .catch(err => {
          console.error(err);
          message.error(err.message || 'Error on updating profile!');
        })
    })
  }

  handleCancel = () => this.setState({previewVisible: false});

  handleChange = (info) => {
    console.log(info);

    const status = info.file.status;
    if (status !== 'uploading') {

    }

    if (status === 'done') {

      const {file} = info;

      if (!this.state.uploadedFile.includes(file.name)) {
        this.state.uploadedFile.push(file.name);
      } else {
        return false;
      }

      this.authStore.updateProfile({
        avatar: file.response.path,
      });

      message.success(`${info.file.name} file uploaded successfully.`);

    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  };

  @bind
  customUpload({file}) {
    this.setState({
      uploading: true
    });
    this.http.upload(file)
      .then(res => {
        return this.authStore.updateProfile({
          avatar: res.path,
        });
      })
      .then(res => {
        message.success(`${file.name} file uploaded successfully.`);
        this.setState({
          uploading: false
        })
      })
  }

  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
    })
  };

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

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

  render() {

    console.log(this.appstate.userData);

    const {userData} = this.appstate;

    const styles = {
      root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
      },
      gridList: {
        width: 500,
        height: 450,
        overflowY: 'auto',
      },
    };

    const {previewVisible, previewImage, fileList} = this.state;

    const {getFieldDecorator} = this.props.form;

    const uploadButton = (
      <div>
        <Icon type="cloud-upload-o" style={{fontSize: "36px", color: "#c3c3c3"}}/>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 14
        }
      }
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 6
        }
      }
    };

    const nameRule = getFieldDecorator('fullname', {
      rules: [
        {
          required: true,
          message: 'name cannot be empty'
        }
      ],
      initialValue: this.authStore.userProfile.fullname
    });

    const mailRule = getFieldDecorator('username', {
      rules: [
        {
          required: true,
          message: 'mail cannot be empty'
        }
      ],
      initialValue: this.authStore.userProfile.username
    });

    const oldPasswordRule = getFieldDecorator('old_password', {
      rules: [
        {
          type: 'string',
          validator: (rule, value, cb) => {
            const {form} = this.props;
            const passwordValue = form.getFieldValue('password');

            if (value && !passwordValue) {
              form.setFields({
                password: {
                  errors: [
                    {
                      message: 'New password cannot be empty!'
                    }
                  ]
                }
              });

              return cb()
            }

            cb();
          }
        }
      ]
    });

    const passwordRule = getFieldDecorator('password', {
      rules: [
        {
          type: 'string',
          validator: (rule, value, cb) => {
            const {form} = this.props;
            const oldPasswordValue = form.getFieldValue('old_password');

            if (value && !oldPasswordValue) {
              form.setFields({
                old_password: {
                  errors: [
                    {
                      message: 'Old password cannot be empty!'
                    }
                  ]
                }
              });

              return cb()
            }

            cb();
          }
        }
      ]
    });

    return (

      <div className="">
            <div className="col s12" style={{transition: "opacity .2s ease-in-out"}}>
              <Card className="row" style={{marginBottom: 10}}>
                <div className="flexSpaceBetween" style={{padding: 16}}>
                  <CardTitle style={{padding: 0, fontSize: 22}} titleStyle={{fontSize: 22}} title="PASSWORD"/>
                  <ToolbarGroup>
                    {/*<RaisedButton*/}
                      {/*icon={<ModeEdit/>}*/}
                      {/*label="Update Password"*/}
                      {/*onClick={this.handleEditPassword}*/}
                      {/*primary={true}/>*/}
                  </ToolbarGroup>
                </div>
              </Card>
              <Card style={{marginBottom:10}}>
                <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                  <ToolbarGroup>
                    <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d', textTransform: 'capitalize'}}
                                  text={'Details'}/>
                  </ToolbarGroup>
                </Toolbar>
                <Divider/>
                <CardText>
                  <div className="row">
                    <div className="col s12 m12 l6">
                      <p className="label-form">Old Password</p>
                      <TextField
                        fullWidth={true}
                        disabled={this.state.disabled}
                        value={this.state.old_password}
                        onChange={(event)=>this.setState({
                          old_password : event.target.value
                        })}
                        type="password"
                        underlineDisabledStyle={{borderBottom:'1px dotted rgba(0, 0, 0, 0.3)'}}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m12 l6">
                      <p className="label-form">Password</p>
                      <TextField
                        fullWidth={true}
                        disabled={this.state.disabled}
                        value={this.state.password}
                        onChange={this.handleChangePassword}
                        type="password"
                        underlineDisabledStyle={{borderBottom:'1px dotted rgba(0, 0, 0, 0.3)'}}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m12 l6">
                      <p className="label-form">Retype Password</p>
                      <TextField
                        fullWidth={true}
                        disabled={this.state.disabled}
                        value={this.state.retype}
                        onChange={this.handleRetype}
                        type="password"
                        errorText={this.state.error_retype}
                        underlineDisabledStyle={{borderBottom:'1px dotted rgba(0, 0, 0, 0.3)'}}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m12 l12">
                      <RaisedButton
                        label="Save"
                        onClick={this.handleSavePassword}
                        style={{visibility: this.state.disabled ? 'hidden' : 'visible' }}
                        primary={true}/>
                    </div>
                  </div>
                </CardText>
              </Card>
            </div>
      </div>
    )
  }
}

export default Form.create()(Password);
