import React from 'react';
import {observer, inject} from 'mobx-react';
import {Form, Input, Button, Select, Upload, Icon, Modal, Spin, message} from 'antd'
import bind from 'bind-decorator';
import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
  FlatButton,
  GridList,
  Paper,
  FloatingActionButton,
  GridTile,
  IconButton, ToolbarGroup, Toolbar, TextField, Divider, ToolbarTitle, TableBody, TableRow, TableRowColumn,
  TableHeaderColumn, Table, TableHeader, RaisedButton, Dialog, SelectField, MenuItem,
} from 'material-ui';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import ContentAdd from 'material-ui/svg-icons/content/add';
import AddIcon from 'material-ui/svg-icons/content/add';
import ModeEdit from 'material-ui/svg-icons/editor/mode-edit';

const {Option, OptGroup} = Select;
const FormItem = Form.Item;
import EmptyComponent from '../../EmptyComponent';
// import './style.scss';
import {appConfig} from "../../../config/app";
import ProfilePhoto from '../Modal/ProfilePhoto';

@inject('appstate')
@observer
class Bank extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.bankStore = props.appstate.bank;
    this.state = {
      currency: '',
      previewVisible: false,
      previewImage: '',
      fileList: [{
        uid: -1,
        name: 'xxx.png',
        status: 'done',
        url: 'http://lorempixel.com/400/400/abstract/',
      }],
      uploadedFile: [],
      uploading: false,
      openedDialogBank: false,
      openedDialog: false,
      openedEditDialog: false,
      openedDialogProfile: false,
      openedDialogPhoto: false
    };
    this.defaultState = Object.assign({}, this.state);
    this.http = props.appstate.http;
    this.authStore = props.appstate.auth;
    this.globalUI = props.appstate.globalUI;
    this.currency = props.appstate.currencyStore;
    this.appstate = props.appstate;
    this.profileStore = props.appstate.profile;
  }

  componentDidMount() {
    this.bankStore.getByUserID('tesss');
    this.currency.getAll();
    this.profileStore.getProfile();
  }

  handleCancel = () => this.setState({previewVisible: false});

  handleCloseBank = () => {
    this.setState({
      openedDialogBank: false
    })
  }

  handleOpenBank = () => {
    this.setState({
      openedDialogBank: true
    })
  }

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

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

  handleChangeBankName = (event) => {
    this.bankStore.data.name = event.target.value;
  };

  handleChangeCurrency = (event, index, value) => {
    this.bankStore.data.currency_id = value.id;
    this.setState({currency: value});
  };

  handleChangeAccount = (event) => {
    this.bankStore.data.account_number = event.target.value;
  };

  handleChangeOnBehalf = (event) => {
    this.bankStore.data.on_behalf = event.target.value;
  };

  postDataBank = () => {
    this.bankStore.post();
    this.setState({
      openedDialogBank: false,
      openedDialog: false
    });
  };

  handleChangeName = (event) => {
    this.authStore.userProfile.agent.name = event.target.value;
    ;
  };

  handleChangePhoneNumber = (event) => {
    this.authStore.userProfile.agent.phone_number = event.target.value;
  };

  handleChangeEmail = (event) => {
    this.authStore.userProfile.agent.email = event.target.value;
  };

  handleChangeAddress = (event) => {
    this.authStore.userProfile.agent.address = event.target.value;
  };

  handleChangePassport = (event) => {
    this.authStore.userProfile.agent.passport_number = event.target.value;
  };

  handleChangeIDNumber = (event) => {
    this.authStore.userProfile.agent.id_number = event.target.value;
  };

  handleChangeTax = (event) => {
    this.authStore.userProfile.agent.id_tax_number = event.target.value;
  };

  handleChangeIDType = (event, target, value) => {
    this.authStore.userProfile.agent.id_type = value;
  };

  editData = () => {
    this.authStore.updateProfile().then(res => {
      this.authStore.getProfile();
      this.setState({openedDialogProfile: false});
      this.setState({openedDialogPhoto: false});
      this.globalUI.openSnackbar("Success Edited Profile");
    });
  };

  handleCloseDialogProfile = () => {
    this.setState({
      openedDialogProfile: false
    })
  };

  handleOpenDialogProfile = () => {
    this.setState({
      openedDialogProfile: true
    })
  };

  handleClosePhoto = () => {
    this.setState({
      openedDialogPhoto: false
    })
  };

  handleOpenPhoto = () => {
    this.setState({
      openedDialogPhoto: true,
      oldPassportPhoto: this.authStore.userProfile.agent.passport_photo,
      oldIdPhoto: this.authStore.userProfile.agent.id_photo,
    });
  }

  handleClosePhoto = () => {
    this.setState({
      openedDialogPhoto: false
    });
    this.authStore.userProfile.agent.passport_photo = this.state.oldPassportPhoto;
    this.authStore.userProfile.agent.id_photo = this.state.oldIdPhoto;
  }

  render() {

    console.log(this.appstate.userData);

    const {userData} = this.appstate;

    const actionsBank = [
      <FlatButton
        label="No"
        primary={true}
        style={{marginRight: 10}}
        onClick={this.handleCloseBank}
      />,
      <RaisedButton
        label="Yes"
        primary={true}
        onClick={this.handleOpen}
      />,
    ]

    const actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        style={{marginRight: 10}}
        onClick={this.handleClose}
      />,
      <RaisedButton
        label="Submit"
        primary={true}
        onClick={() => this.postDataBank()}
      />,
    ];

    const actionsProfile = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleCloseDialogProfile}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        onClick={() => this.editData()}
      />,
    ];

    const actionsPhoto = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleClosePhoto}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        onClick={() => this.editData()}
      />,
    ];

    const idType = [
      <MenuItem key={1} value={"Driver License"} primaryText="Driver License"/>,
      <MenuItem key={2} value={"Resident ID Card"} primaryText="Resident ID Card"/>,
    ];

    const styles = {
      root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
      },
      gridList: {
        width: 500,
        height: 450,
        overflowY: 'auto',
      },
    };

    const {previewVisible, previewImage, fileList} = this.state;

    const {getFieldDecorator} = this.props.form;

    const uploadButton = (
      <div>
        <Icon type="cloud-upload-o" style={{fontSize: "36px", color: "#c3c3c3"}}/>
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 6
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 14
        }
      }
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 6
        }
      }
    };

    const nameRule = getFieldDecorator('fullname', {
      rules: [
        {
          required: true,
          message: 'name cannot be empty'
        }
      ],
      initialValue: this.authStore.userProfile.fullname
    });

    const mailRule = getFieldDecorator('username', {
      rules: [
        {
          required: true,
          message: 'mail cannot be empty'
        }
      ],
      initialValue: this.authStore.userProfile.username
    });

    const oldPasswordRule = getFieldDecorator('old_password', {
      rules: [
        {
          type: 'string',
          validator: (rule, value, cb) => {
            const {form} = this.props;
            const passwordValue = form.getFieldValue('password');

            if (value && !passwordValue) {
              form.setFields({
                password: {
                  errors: [
                    {
                      message: 'New password cannot be empty!'
                    }
                  ]
                }
              });

              return cb()
            }

            cb();
          }
        }
      ]
    });

    const passwordRule = getFieldDecorator('password', {
      rules: [
        {
          type: 'string',
          validator: (rule, value, cb) => {
            const {form} = this.props;
            const oldPasswordValue = form.getFieldValue('old_password');

            if (value && !oldPasswordValue) {
              form.setFields({
                old_password: {
                  errors: [
                    {
                      message: 'Old password cannot be empty!'
                    }
                  ]
                }
              });

              return cb()
            }

            cb();
          }
        }
      ]
    });

    return (

      <div className="containerMiddle">
        <div className="row">
          <div className="col s12" style={{transition: "opacity .2s ease-in-out"}}>
            <Card className="animated fadeIn cardLite">
              <ToolbarGroup className="flexSpaceBetween" style={{padding: "0px 16px 0px 16px"}}>
                <ToolbarTitle style={{fontSize: 14, fontWeight: 500, color: '#32325d', textTransform: 'capitalize'}}
                              text={'Banks'}/>
                <RaisedButton
                  icon={<ModeEdit/>}
                  label="Add"
                  style={{marginRight: 0}}
                  onClick={this.handleOpenBank}
                  primary={true}/>
              </ToolbarGroup>
              <Divider/>
              <div style={{paddingBottom: 5}}>
                <Table selectable={false} fixedHeader={true} style={{maxHeight: 'calc(100vh - 250px)'}}>
                  <TableHeader displaySelectAll={false}
                               adjustForCheckbox={false}
                               enableSelectAll={false}>
                    <TableRow style={{height: 38, background: '#f6f9fc'}}>
                      <TableHeaderColumn className="TableHeaderColumnAkun"
                                         style={{height: 'auto'}}>Name</TableHeaderColumn>
                      <TableHeaderColumn className="TableHeaderColumnAkun"
                                         style={{height: 'auto'}}>Account</TableHeaderColumn>
                      <TableHeaderColumn className="TableHeaderColumnAkun" style={{height: 'auto'}}>On
                        Behalf</TableHeaderColumn>
                    </TableRow>
                  </TableHeader>
                  <TableBody displayRowCheckbox={false}>
                    {!this.bankStore.isEmpty ? this.bankStore.list.map((item) => {
                        return (
                          <TableRow>
                            <TableRowColumn>{item.name}</TableRowColumn>
                            <TableRowColumn>{item.account_number}</TableRowColumn>
                            <TableRowColumn>{item.on_behalf}</TableRowColumn>
                          </TableRow>
                        );
                      }) :
                      <TableRow>
                        <TableRowColumn colSpan="4" style={{textAlign: "center"}}>
                          <EmptyComponent type="empty" header="" content="There is no data in sight"/>
                        </TableRowColumn>
                      </TableRow>
                    }
                  </TableBody>
                </Table>
              </div>
            </Card>
            {/* {userData.role == 'agent' ? (
              <Dialog
                title="Update Profile"
                actions={actionsProfile}
                modal={true}
                open={this.state.openedDialogProfile}
                onRequestClose={() => this.handleCloseDialog()}
              >
                <div style={{padding: 20}}>
                  <div className="row">
                    <div className="col s12 m6 l6">
                      <p className="label-form">Agent Name</p>
                      <TextField
                        hintText="E.g. Michael Jordan"
                        fullWidth={true}
                        onChange={this.handleChangeName}
                        value={this.authStore.userProfile.agent.name}
                      />
                    </div>
                    <div className="col s12 m6 l6">
                      <p className="label-form">Phone Number</p>
                      <TextField
                        hintText="E.g. 08999764787"
                        fullWidth={true}
                        onChange={this.handleChangePhoneNumber}
                        type="number"
                        value={this.authStore.userProfile.agent.phone_number}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m6 l6">
                      <p className="label-form">Email</p>
                      <TextField
                        hintText="E.g. Michaeljordan@gmail.com"
                        fullWidth={true}
                        type="email"
                        onChange={this.handleChangeEmail}
                        value={this.authStore.userProfile.agent.email}
                      />
                    </div>
                    <div className="col s12 m6 l6">
                      <p className="label-form">Address</p>
                      <TextField
                        hintText="E.g. Jl. Kemayoran Baru No.55"
                        fullWidth={true}
                        multiLine={true}
                        rowsMax={4}
                        onChange={this.handleChangeAddress}
                        value={this.authStore.userProfile.agent.address}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m6 l6">
                      <p className="label-form">ID Type</p>
                      <SelectField
                        fullWidth={true}
                        value={this.authStore.userProfile.agent.id_type}
                        onChange={this.handleChangeIDType}
                      >
                        {idType}
                      </SelectField>
                    </div>
                    <div className="col s12 m6 l6">
                      <p className="label-form">ID Number</p>
                      <TextField
                        hintText="E.g. 1381273817239"
                        fullWidth={true}
                        value={this.authStore.userProfile.agent.id_number}
                        onChange={this.handleChangeIDNumber}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div className="col s12 m6 l6">
                      <p className="label-form">ID Tax Number</p>
                      <TextField
                        hintText="E.g. 092572943407000"
                        fullWidth={true}
                        value={this.authStore.userProfile.agent.id_tax_number}
                        onChange={this.handleChangeTax}
                      />
                    </div>
                    <div className="col s12 m6 l6">
                      <p className="label-form">Passport Number</p>
                      <TextField
                        hintText="E.g. X000000000"
                        fullWidth={true}
                        value={this.authStore.userProfile.agent.passport_number}
                        onChange={this.handleChangePassport}
                      />
                    </div>
                  </div>
                </div>
              </Dialog>
            ) : ( '' )} */}
            <Dialog
              title="Adding Bank"
              actions={actionsBank}
              modal={true}
              open={this.state.openedDialogBank}
              onRequestClose={() => this.handleCloseBank()}
            >
              <div style={{padding: 20}}>
                <div className="row">
                  <div className="col s12 m6 l6">
                    <p className="label-form">Name</p>
                    <TextField
                      hintText=" E.g. BCA"
                      onChange={this.handleChangeBankName}
                      fullWidth={true}
                    />
                  </div>
                  <div className="col s12 m6 l6">
                    <p className="label-form">Currency</p>
                    <SelectField
                      fullWidth={true}
                      value={this.state.currency}
                      onChange={this.handleChangeCurrency}
                    >
                      {this.currency.currencyList.map(item => {
                        return (<MenuItem value={item} primaryText={item.name}/>)
                      })}
                    </SelectField>
                  </div>
                </div>

                <div className="row">
                  <div className="col s12 m6 l6">
                    <p className="label-form">Account</p>
                    <TextField
                      hintText=" E.g. xxxxxxxxxx"
                      onChange={this.handleChangeAccount}
                      fullWidth={true}
                      type="number"
                    />
                  </div>
                  <div className="col s12 m6 l6">
                    <p className="label-form">On Behalf</p>
                    <TextField
                      hintText=" E.g. Ridwan Abadi"
                      onChange={this.handleChangeOnBehalf}
                      fullWidth={true}
                    />
                  </div>
                </div>
              </div>
            </Dialog>
            {userData.role == 'agent' ? (
              <Dialog
                title="Update Agent"
                actions={actionsPhoto}
                modal={true}
                open={this.state.openedDialogPhoto}
                onRequestClose={() => this.handleClosePhoto()}
              >
                <ProfilePhoto/>
              </Dialog>
            ) : ( <div></div> )}
            <Dialog
              title="Warning"
              actions={actions}
              modal={true}
              open={this.state.openedDialog}
              onRequestClose={() => this.handleClose()}
            >
              Make sure all of your data is correct before submitting.
            </Dialog>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(Bank);
