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 FormData from './FormData';
import ArrowForwardIcon from 'material-ui/svg-icons/navigation/arrow-forward';
import NavigationArrowBack from 'material-ui/svg-icons/navigation/arrow-back';
import {constant} from "../../../../config/const";
import schema from 'async-validator'

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

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

  componentDidMount() {
    console.log(this.state.formData,'ini men')
    this.setState({
      stepIndex: 0
    });

  }

  onChangeForm(formData) {
    this.setState({formData});
  }

  getStepContent(stepIndex) {

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

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

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

  handleNext = () => {
    const {stepIndex} = this.state;
    const {mode = "create", defaultValue = {}} = this.props;
    if (stepIndex === 0) {

      const rules = {
        preorder_store_note: [
          {
            required: true,
            message: 'Please input your note'
          }
        ],
        preorder_price: [
          {
            required: true,
            message: 'Please input price'
          }
        ],
        preorder_weight: [
          {
            required: true,
            message: 'Please input weight'
          }
        ]
      };

      const validator = new schema(rules);

      if (mode === "create") {
        console.log(this.state.formData, 'this is form data');
        validator.validate(this.state.formData, (errs, f) => {
          console.log(errs);
          if (errs) {
            this.globalUI.showNotification("Something's Wrong", errs[0].message);
          } else {
            if(this.state.formData.preorder_weight > this.state.formData.item_stock_available){
              this.globalUI.showNotification("Something's Wrong", 'Stock Not Enough');
            }
            else if (this.state.formData.preorder_price > 0 && this.state.formData.preorder_weight > 0) {
              this.setState({
                stepIndex: stepIndex + 1,
              });
            }
            else{
              this.globalUI.showNotification("Something's Wrong", 'Price or weight cannot be 0');
            }
          }
        });
      }
      else if (mode === "update") {
        this.setState({
          stepIndex: stepIndex + 1,
        });
      }

    }
  }

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

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

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

    if (mode === "create") {
      let data = this.state.formData;

      this.orderStore.addStoreNotes(data)
        .then(res => {
          this.globalUI.hideDialogLoading();
          this.globalUI.openSnackbar("Success Added Notes");
          this.orderStore.getDetail(data.order_store_id);
          this.setState({
            stepIndex: 0
          })
        })
        .catch(err => {
          console.error(err);
        });
    } else if (mode === "update") {
      // let data = this.state.formData;
      // // data.image = {
      // //   icon : this.state.formData.icon,
      // //   background_image : this.state.formData.background_image
      // // }
      // // delete data.icon;
      // // delete data.background_image;
      // this.categoriesStore.putCategory(defaultValue.id, data)
      //   .then(res => {
      //     // this.globalUI.hideDialog(DIALOG.EMPLOYEE.CREATE);
      //     this.globalUI.hideDialogLoading();
      //     this.globalUI.openSnackbar("Success Updated Category")
      //     this.setState({
      //       stepIndex: 0
      //     })
      //     // this.categoriesStore.getAll();
      //   })
      //   .catch(err => {
      //     this.globalUI.openSnackbar("Error, Check log for detail");
      //     console.error(err);
      //   });
    }
  }

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

  continueButton() {
    console.log(this.props.defaultValue,'iniiiiiii')
    if (!!this.props.defaultValue.preorder_store_note) {
      console.log('ALREADY ADDED');
      return;
    }

    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") ? "Preorder Request" : "Update Preorder Request"} </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}}>Confirmation</StepLabel>
                </Step>
                 <Step>
                  <StepLabel style={{padding: "0px 0px 0px 14px", height: 52}}>Confirm</StepLabel>
                </Step>
              </Stepper>
            </div>
          </div>}s
          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.ORDER.PREORDER_ADD_NOTES) : this.handlePrev()}
            />
            {this.continueButton()}
          </div>}
          autoScrollBodyContent={true}
          repositionOnUpdate={true}
          open={this.globalUI[DIALOG.ORDER.PREORDER_ADD_NOTES]}
          onRequestClose={this.handleClose}
          bodyStyle={{padding:'0 8px 8px 8px'}}
          overlayStyle={{zIndex: 999}}
          style={{zIndex: 9999}}
          paperClassName={'radius6'}
          contentClassName={'marketplace-dialog-small'}
        >
          <div>
            {this.getStepContent(stepIndex)}
          </div>

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


      </div>
    )
  }
}
