import React from 'react';
import {observer, inject} from 'mobx-react';
import {
  Dialog, FlatButton, RaisedButton,
  Step,
  StepLabel,
  Stepper,
  IconButton
} from "material-ui";
import {DIALOG} from "../../../../stores/global_ui";
import BankInformation from './BankInformation';
import schema from 'async-validator'

@inject('appstate')
@observer
export default class BankAddDialog extends React.Component {

  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      stepIndex: 0,
      finished: false,
      openedDialog: false,
      formData: {},
      errorMessage: ''
    };
    this.defaultState = Object.assign({}, this.state);
    this.globalUI = props.appstate.globalUI;
    this.userBanks = props.appstate.userBanks;
    this.userData = props.appstate.userData;
  }

  componentDidMount() {
    this.setState({
      stepIndex: 0
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({stepIndex: 0, formData: nextProps.defaultValue});
  }

  getStepContent(stepIndex) {

    const {mode = "create", defaultValue = {}} = this.props;

    switch (stepIndex) {
      case 0:
        return (
          <BankInformation
            mode={mode}
            defaultValue={defaultValue}
            onChangeData={formData => this.setState({formData})}/>
        );
      // case 1:
      // return <IdentificationPassport/>;
    }
  }

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

  handleNext = () => {
    const {stepIndex} = this.state;
    if (stepIndex === 0) {

      const rules = {
        on_behalf: [
          {
            required: true,
            message: "Please fill on behalf"
          },
          {
            type: 'string',
            message: 'On behalf must be alphabet only'
          }
        ],
        account_number: [
          {
            required: true,
            message: 'Please fill first name',
          }
        ],
        name: [
          {
            required: true,
            message: 'Please enter a bank name',
          }
        ]
      };

      const validator = new schema(rules);
      console.log(this.state.formData);
      validator.validate(this.state.formData, (errs, f) => {
        console.log(errs);

        if (errs) {
          this.globalUI.showNotification("Something's Wrong", errs[0].message);
        } else {
          this.setState({
            stepIndex: stepIndex + 1,
          });
        }
      });
    }
  }

  handlePrev = () => {
    const {stepIndex} = this.state;
    if (stepIndex > 0) {
      this.setState({stepIndex: stepIndex - 1});
    }
  }

  save = () => {
    this.globalUI.hideDialog(DIALOG.STORES.CREATE);
    this.globalUI.showDialogLoading();
    const {mode = "create", defaultValue = {}} = this.props;

    if(this.userData.role === 'store') {
      if (mode === "create") {
        // console.log(this.state.formData);
        this.userBanks.addBank(this.state.formData).then(res => {
          this.globalUI.openSnackbar('Successfully add new bank');
        }).catch((err) => {
          console.log(err);
          this.globalUI.closeLoading();
        })
      } else if (mode === "update") {
        this.userBanks.updateBank(this.state.formData).then(res => {
          this.globalUI.openSnackbar('Successfully update bank');
        }).catch(err => {
          console.log(err);
          this.globalUI.openSnackbar('Something Error');
        })
        // this.employeeStore.update(defaultValue.id, this.state.formData)
        //   .then(res => {
        //     // this.globalUI.hideDialog(DIALOG.STORES.CREATE);
        //     this.globalUI.hideDialogLoading();
        //     this.globalUI.openSnackbar("Success Updated New Employee")
        //     this.setState({
        //       stepIndex: 0
        //     })
        //     // this.employeeStore.getAll();
        //   })
        //   .catch(err => {
        //     console.error(err);
        //   });
      }
    }
    else if(this.userData.role === 'administrator') {
      if (mode === "create") {
        // console.log(this.state.formData);
        this.userBanks.addBankAdmin(this.props.id,this.state.formData).then(res => {
          this.globalUI.openSnackbar('Successfully add new bank');
          console.log(this.props.id);
        }).catch((err) => {
          console.log(err);
          this.globalUI.closeLoading();
        })
      } else if (mode === "update") {
        this.userBanks.updateBankAdmin(this.props.id,this.state.formData).then(res => {
          this.globalUI.openSnackbar('Successfully update bank');
        }).catch(err => {
          console.log(err);
          this.globalUI.openSnackbar('Something Error');
        })
        // this.employeeStore.update(defaultValue.id, this.state.formData)
        //   .then(res => {
        //     // this.globalUI.hideDialog(DIALOG.STORES.CREATE);
        //     this.globalUI.hideDialogLoading();
        //     this.globalUI.openSnackbar("Success Updated New Employee")
        //     this.setState({
        //       stepIndex: 0
        //     })
        //     // this.employeeStore.getAll();
        //   })
        //   .catch(err => {
        //     console.error(err);
        //   });
      }
    }

  }

  handleClose = () => {
    this.setState({confirmationDialog: false, formData: {}})
  };

  handlePost = () => {
    // this.agentStore.post().then(res => {
    //   this.props.history.push(LINKS.SETTING);
    //   this.globalUI.openSnackbar("Successfull Added Employee");
    // });
  };

  continueButton() {
    if (this.state.stepIndex === 1) {
      return (
        <RaisedButton
          label="Finish"
          primary={true}
          onClick={this.save}
        />
      );
    } else {
      return (
        <RaisedButton
          label="Next"
          primary={true}
          onClick={this.handleNext}
        />
      );
    }
  }

  render() {

    const {finished, stepIndex} = this.state;
    const {mode = "create", defaultValue = {}} = this.props;

    const actions = [
      <RaisedButton
        label="OK"
        primary={true}
        style={{marginRight: 10}}
        onClick={this.handleClose}
      />,
    ];

    const title =
      <div>
        <h4 style={{
          fontSize: 26,
          marginBottom: 0,
          marginTop: 0,
          fontWeight: 500,
          color: "black"
        }}>{(mode === "create") ? "Add New" : "Update"} Bank Account</h4>
      </div>
    ;

    return (
      <div>
        <Dialog
          title={<div>
            <div>{title}</div>
            <div style={{padding: "0px 14px 0px 0px", marginTop: 10}}>
              {/*<Stepper activeStep={stepIndex}>*/}
              {/*<Step>*/}
              {/*<StepLabel style={{padding: "0px 14px 0px 0px", height: 52}}>Bank Account</StepLabel>*/}
              {/*</Step>*/}
              {/*/!* <Step>*/}
              {/*<StepLabel style={{padding: "0px 0px 0px 14px", height: 52}}>Identification & Passport</StepLabel>*/}
              {/*</Step> *!/*/}
              {/*</Stepper>*/}
            </div>
          </div>}
          titleStyle={{paddingBottom: 10}}
          modal={false}
          actions={<div style={{marginTop: 12}}>
            <FlatButton
              label={(stepIndex === 0) ? "Cancel" : "Back"}
              style={{marginRight: 10}}
              primary={true}
              onClick={() => (stepIndex === 0) ? this.globalUI.hideDialog(DIALOG.STORES.CREATE) : this.handlePrev()}
            />
            {this.continueButton()}
          </div>}
          autoScrollBodyContent={true}
          repositionOnUpdate={true}
          open={this.globalUI[DIALOG.STORES.CREATE]}
          onRequestClose={this.handleClose}
          style={{zIndex: 999}}
          paperClassName={'radius6'}
          contentClassName={'marketplace-dialog-small'}
        >
          <div style={{marginTop: 20}}>
            {this.getStepContent(stepIndex)}
          </div>
        </Dialog>

        <Dialog
          title="Warning"
          actions={actions}
          modal={false}
          autoScrollBodyContent={false}
          contentStyle={{width: 350}}
          open={this.state.confirmationDialog}
          onRequestClose={() => this.handleClose()}
        >
          {this.state.errorMessage}
        </Dialog>
      </div>
    )
  }
}
