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 CategoryData from './CategoryData';
import ArrowForwardIcon from 'material-ui/svg-icons/navigation/arrow-forward';
import NavigationArrowBack from 'material-ui/svg-icons/navigation/arrow-back';
import schema from 'async-validator'

@inject('appstate')
@observer
export default class ItemDialog 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.customMenu = props.appstate.custom_menu;
  }

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

  }

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

  getStepContent(stepIndex) {

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

    switch (stepIndex) {
      case 0:
        return (
          <CategoryData
            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 = {
        name: [
          {
            required: true,
            message: 'Please insert name'
          }
        ],
        icon: [
          {
            required: true,
            message: 'Please insert icon'
          }
        ],
      };

      if(this.state.formData.type == 'url'){
        rules.url = [
          {
            required : true,
            message :'Please insert valid url'
          }
        ]
      }
      else if(this.state.formData.type == "post"){
        rules.tag = [
          {
            required : true,
            message : "Please insert post category"
          }
        ];

        rules.post_template = [
          {
            required : true,
            message : "Please insert post template"
          }
        ]
      }

      const validator = new schema(rules);

      validator.validate(this.state.formData, (errs, f) => {
        console.log(errs);
        if (errs) {
          console.log(this.state.formData,'this is form data');
          this.globalUI.showNotification("Something's Wrong", errs[0].message);
        } else {
          // if(this.state.formData.type == 'url' && !this.state.formData.url){
          //   this.globalUI.showNotification("Something's Wrong", 'Please input url',this.state.formData);
          //   return;
          // }
          // else if(this.state.formData.type == 'post' && !this.state.formData.tag){
          //   console.log(this.state.formData,'==========');
          //   this.globalUI.showNotification("Something's Wrong", 'Please input tag');
          //   return;
          // }

          this.setState({
            stepIndex: stepIndex + 1,
          });
        }
      });
    }
  };

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

  closeDialog = ()=>{
    this.customMenu.formData.name = "";
    this.customMenu.formData.url = "";
    this.globalUI.hideDialog(DIALOG.CUSTOM_MENU.CREATE)
  }

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

  save = () => {
    this.globalUI.hideDialog(DIALOG.CUSTOM_MENU.CREATE);
    this.globalUI.showDialogLoading();
    const {mode="create", defaultValue={}} = this.props;
    let data = this.state.formData;
    data.additional_data = (data.type == 'post') ? {tag_id : data.tag,template : data.post_template} :{};
    delete data.tag;
    delete data.post_template;

    if (mode === "create") {
      if(data.icon == ''){
        data.icon = 'buffer';
      }
      this.customMenu.create(data)
        .then(res => {
          this.globalUI.hideDialogLoading();
          this.globalUI.openSnackbar("Success Added New Custom Menu");
          this.setState({
            stepIndex: 0
          });
        })
        .catch(err => {
          this.globalUI.hideDialogLoading();
          this.globalUI.openSnackbar("Something Goes Wrong");
          this.setState({
            stepIndex: 0
          });
          console.error(err);
        });
    } else if (mode === "update") {

      if(data.icon == ''){
        data.icon = 'buffer';
      }
      this.customMenu.update(defaultValue.id, this.state.formData)
        .then(res => {
          // this.globalUI.hideDialog(DIALOG.EMPLOYEE.CREATE);
          this.globalUI.hideDialogLoading();
          this.globalUI.openSnackbar("Success Updated")
          this.setState({
            stepIndex: 0
          })
          // this.classStore.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() {
    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" : "Update"} Custom Menu</h4>
      </div>
    ;

    return (
      <div>
        <Dialog
          title={<div>
            <div>{title}</div>
            <div style={{padding: "0px 14px 0px 0px"}}>
              <Stepper activeStep={stepIndex}>
                <Step>
                  <StepLabel style={{padding: "0px 14px 0px 0px"}}>Menu Data</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.closeDialog() : this.handlePrev()}
            />
            {this.continueButton()}
          </div>}
          autoScrollBodyContent={true}
          repositionOnUpdate={true}
          open={this.globalUI[DIALOG.CUSTOM_MENU.CREATE]}
          onRequestClose={this.handleClose}
          style={{zIndex: 999}}
        >
          <div>
            {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>
    )
  }
}
