import React from 'react';
import {observer, inject} from 'mobx-react';
import {Dialog, FlatButton, RaisedButton, Step, StepLabel, Stepper} from "material-ui";
import {DIALOG} from "../../stores/global_ui";
import Form from './WithdrawForm';
import Review from './WithdrawReview';
import get from 'lodash.get';

@inject('appstate')
@observer
export default class WithdrawDialogComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.globalUI = props.appstate.globalUI;
    this.withdraw = props.appstate.withdraw;
    this.bankStore = props.appstate.bank;
    this.transactionStore = props.appstate.transaction;
    this.state = {
      currentStep: 0,
      openedDialog: false,
      nextButtonText: 'Next',
      backButtonText: 'Cancel',
      formData: {},
      steps: [
        {
          label: 'Withdraw Form',
          // action: () => this.validateName(),
          component: <Form onFormChange={(formData) => this.setState({formData})} />,
          nextButtonText: 'Review',
          backButtonText: 'Cancel',
        },
        {
          label: "Review",
          component: <Review/>,
          action: this.createWithdraw,
          nextButtonText: 'Withdraw',
          backButtonText: 'Back',
        }
      ]
    };

    this.defaultState = Object.assign({}, this.state);

  }

  componentDidMount() {
    // this.bankStore.getAll();
  }

  get stepperContent() {
    const {currentStep, steps} = this.state;

    return steps[currentStep].component || (<div>Step #{currentStep}</div>);
  }

  handleNext() {
    const {currentStep, steps} = this.state;
    let newStep = currentStep;
    let regex=/^[0-9]+$/;
    if(this.withdraw.data.bank_name === '' || this.withdraw.data.amount === ''){
      this.handleOpen();
    }else if(this.withdraw.data.amount.match(regex) && newStep < steps.length){
      newStep = currentStep + 1;
    }else{
      this.handleOpen();
    }

    // if (newStep >= steps.length) {
    //   this.setState({currentStep:0});
      // this.withdraw.createWithdraw().then(res => {
      //   this.globalUI.openSnackbar("Request Withdraw Success");
      //   this.transactionStore.getAll();
      //   this.withdraw.data = {
      //     amount: '',
      //     bank_account_number: '',
      //     bank_name: '',
      //   };
      //   this.withdraw.bank = {
      //     name: '',
      //     account_number: ''
      //   };
      // }).catch(err => this.globalUI.openSnackbar(err.message));
      // this.globalUI.openSnackbar('cannot use this at this moment');
      // this.closeModal();
    // }
    (steps[currentStep].action || (() => Promise.resolve(true)))()
      .then(status => {
        this.setState({
          currentStep: (newStep >= steps.length) ? 0 : newStep,
          nextButtonText: (newStep >= steps.length) ? this.defaultState.nextButtonText : steps[newStep].nextButtonText ,
          backButtonText: (newStep >= steps.length) ? this.defaultState.backButtonText : steps[newStep].backButtonText,
        });

        if(newStep >= steps.length){
            this.globalUI.openSnackbar(status.message);
            this.transactionStore.getAll();
            this.closeModal();
        }
      })
      .catch(err => {
        this.globalUI.openSnackbar(err.message);
      })
  }

  createWithdraw = ()=>{
    return new Promise((resolve,reject)=>{
       this.withdraw.createWithdraw().then(res=>{
          resolve(res)
       }).catch(err=>{
         reject(err)
       })
    })
  };

  handlePrev() {
    const {currentStep, steps} = this.state;
    let newStep = currentStep - 1;
    if (newStep < 0) {
      this.setState({
        currentStep: 0,
        nextButtonText: steps[0].nextButtonText || this.defaultState.nextButtonText,
        backButtonText: steps[0].backButtonText || this.defaultState.backButtonText
      });
      this.closeModal();
    } else {
      this.setState({
        currentStep: newStep,
        nextButtonText: steps[newStep].nextButtonText || this.defaultState.nextButtonText,
        backButtonText: steps[newStep].backButtonText || this.defaultState.backButtonText,
      })
    }
  }

  closeModal() {
    this.globalUI.hideDialog(DIALOG.WALLET.WITHDRAW);
    this.withdraw.data = {
      amount: '',
      bank_account_number: '',
      bank_name: '',
    };
    this.withdraw.bank = {
      name: '',
      account_number: ''
    };
  }

  handleClose = () => {
    this.setState({openedDialog: false})
  };

  handleOpen = () => {
    this.setState({openedDialog: true})
  };

  render() {

    const actionsWarn = [
      <FlatButton
        label="Okay"
        primary={true}
        style={{marginRight:10}}
        onClick={this.handleClose}
      />,
    ];

    let {
      currentStep,
      nextButtonText:defaultNextText,
      backButtonText:defaultBackText
    } = this.state;

    let nextButtonText, backButtonText;

    backButtonText = get(this.state, `steps[${currentStep}].backButtonText`, defaultBackText);
    nextButtonText = get(this.state, `steps[${currentStep}].nextButtonText`, defaultNextText);

    const actions = [
      <FlatButton
        label={backButtonText}
        onClick={() => this.handlePrev()}
        style={{marginRight: 12}}
      />,
      <RaisedButton
        label={nextButtonText}
        onClick={() => this.handleNext()}
        primary={true}
      />
    ];

    return (
      <div>
        <Dialog
          actions={actions}
          modal={true}
          onRequestClose={()=> this.closeModal()}
          open={this.globalUI[DIALOG.WALLET.WITHDRAW]}>
          <Stepper activeStep={currentStep}>
            {this.state.steps.map(step => {
              return (
                <Step key={step.label}>
                  <StepLabel> <span className="hide-on-small-only">{step.label}</span></StepLabel>
                </Step>
              )
            })}
          </Stepper>
          {this.stepperContent}
        </Dialog>
        <Dialog
          title="Warning"
          actions={actionsWarn}
          modal={true}
          contentStyle={{width:350}}
          open={this.state.openedDialog}
          onRequestClose={()=> this.handleClose()}
        >
          Please Fill the form correctly
        </Dialog>
      </div>
    )
  }
}
