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 './DepositForm';
import Review from './DepositReview';
import get from 'lodash.get';

@inject('appstate')
@observer
export default class DepositDialogComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      currentStep: 0,
      openedDialog: false,
      nextButtonText: 'Next',
      backButtonText: 'Cancel',
      formData: {},
      steps: [
        {
          label: 'Deposit Form',
          // action: () => this.validateName(),
          component: <Form/>,
          nextButtonText: 'Review',
          backButtonText: 'Cancel',
        },
        {
          label: "Review",
          component: () => <Review/>,
          // action: () => this.deposit.createDeposit(this.state.formData),
          nextButtonText: 'Deposit',
          backButtonText: 'Back',
        }
      ]
    };

    this.defaultState = Object.assign({}, this.state);
    this.globalUI = props.appstate.globalUI;
    this.deposit = props.appstate.deposit;
    this.transactionStore = props.appstate.transaction;
  }

  componentDidMount() {
    // console.log('DepositDialogComponent loaded!')
  }

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

    switch (typeof steps[currentStep].component) {
      case "function":
        return steps[currentStep].component();
      default:
        return steps[currentStep].component || (<div>Step #{currentStep}</div>);
    }
  }

  handleNext() {
    const {currentStep, steps} = this.state;
    let newStep = currentStep;
    let regex=/^[0-9]+$/;
    if(this.deposit.data.payment_proof === '' || this.deposit.data.amount === '' || 
       this.deposit.data.bank_account_number === '' || this.deposit.data.bank_name === '' ||
       this.deposit.data.bank_behalf_of === '' || this.deposit.data.bank_to.name === ''){
      this.handleOpen();
    }else if(this.deposit.data.amount.match(regex)){
      newStep = currentStep + 1;
    }else{
      this.handleOpen();
    }

      if (newStep >= steps.length) {
        this.setState({currentStep:0});
        this.deposit.createDeposit().then(res => {
          this.globalUI.openSnackbar("Request Deposit Success");
          this.transactionStore.getAll();
          this.deposit.bankAdmin = {
            name : '',
            account_number : '',
            on_behalf : '',
          };
          this.deposit.data = {
            payment_proof: '',
            amount: '',
            bank_account_number: '',
            bank_name: '',
            bank_behalf_of: '',
            bank_to: {
              name: this.deposit.bankAdmin.name,
              account_number: this.deposit.bankAdmin.account_number,
              on_behalf: this.deposit.bankAdmin.on_behalf,
            },
          };
        });
        this.closeModal();
      }

    (steps[currentStep].action || (() => Promise.resolve(true)))()
      .then(status => {
        this.setState({
          currentStep: newStep,
          nextButtonText: steps[newStep].nextButtonText || this.defaultState.nextButtonText,
          backButtonText: steps[newStep].backButtonText || this.defaultState.backButtonText,
        })
      })
  }

  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.DEPOSIT);
    this.deposit.bankAdmin = {
          name : '',
          account_number : '',
          on_behalf : '',
        };
        this.deposit.data = {
          payment_proof: '',
          amount: '',
          bank_account_number: '',
          bank_name: '',
          bank_behalf_of: '',
          bank_to: {
            name: this.deposit.bankAdmin.name,
            account_number: this.deposit.bankAdmin.account_number,
            on_behalf: this.deposit.bankAdmin.on_behalf,
          },
        };
  }

  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
          title="Deposit Form"
          actions={actions}
          modal={true}
          onRequestClose={()=> this.closeModal()}
          autoScrollBodyContent={true}
          open={this.globalUI[DIALOG.WALLET.DEPOSIT]}>
          <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>
    )
  }
}
