import React from 'react';
import {observer, inject} from 'mobx-react';
import {Form, Input, Button, Select, Upload, Icon, Modal, Spin, message,Card as CardAntd} 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,DatePicker
} 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';
import EditDialog from '../Modal/EditDialog'

let DateTimeFormat = global.Intl.DateTimeFormat;

@inject('appstate')
@observer
class GeneralInformation 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();
  }

  saveProfile() {
    const {form} = this.props;

    form.validateFields((err, fields) => {

      if (err) {
        return console.error(err);
      }

      this.authStore.updateProfile(fields)
        .then(res => {
          message.success('Profile Updated!');
        })
        .catch(err => {
          console.error(err);
          message.error(err.message || 'Error on updating profile!');
        })
    })
  }

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

  

  @bind
  customUpload({file}) {
    this.setState({
      uploading: true
    });
    this.http.upload(file)
      .then(res => {
        return this.authStore.updateProfile({
          avatar: res.path,
        });
      })
      .then(res => {
        message.success(`${file.name} file uploaded successfully.`);
        this.setState({
          uploading: false
        })
      })
  }

  handleOpenEdit = () => {
    this.setState({openedEditDialog: true});
  };

  handleCloseEdit = () => {
    this.setState({openedEditDialog: false});
  };

  editData = () => {
    console.log(this.profileStore.userProfile,'ress');
    this.profileStore.updateProfile().then(res => {
      this.profileStore.getProfile();
      this.setState({openedEditDialog: 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;
  }

  handleChangeFirstName = (event) => {
  	this.profileStore.userProfile.firstname = event.target.value;
  };

  handleChangeLastName = (event) => {
  	this.profileStore.userProfile.lastname  = event.target.value;
  };

  handleChangePlace = (event) => {
  	this.profileStore.userProfile.place_of_birth = event.target.value;
  };

  // handleChangePlaceOfBirth = (event) => {
  //   this.profileStore.userProfile.place_of_birth = event.target.value;
  // };

  handleChangePhone = (event) => {
  	this.profileStore.userProfile.phone  = event.target.value;
  };

  handleChangeDate = (event, date) => {
    this.profileStore.userProfile.date_of_birth  = moment(date).format('YYYY-MM-DD');
  };

  handleChangeGender = (event, index, value) => {
  	this.profileStore.userProfile.gender = value;
  };

  // handleCategory = (event,target,value) =>{
  //   this.setState({gender : value});
  //   this.packageStore.postData.category_id = value;
  // }

  uploaderHandler = (file)=>{
    this.http.upload(file.originFileObj)
      .then(res => {
        this.profileStore.userProfile.photo = res.path;
        this.profileStore.updatePhotoProfile();
        message.success(`${info.file.name} file uploaded successfully.`);
    })
  }

  render() {

    const actionsEdit = [
      <FlatButton
        label="Cancel"
        primary={true}
        style={{marginRight: 10}}
        onClick={this.handleCloseEdit}
      />,
      <RaisedButton
        label="Update Profile"
        primary={true}
        onClick={() => this.editData()}
      />,
    ];

    const Dragger = Upload.Dragger;
   

    const props = {
      name: 'file',
      multiple: true,
      action: `${appConfig.apiUrl}files/`,
      onChange: async (info) => {
        console.log(info, 'info');
        const status = info.file.status;
        if (status === 'done') {
          await this.uploaderHandler(info.file);
          message.success(`${info.file.name} file uploaded successfully.`);
        } else if (status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };

    console.log(this.appstate.userData);

    const {userData} = this.appstate;


    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();
          }
        }
      ]
    });
    const { Meta } = CardAntd;

    return (

      <div className="containerMiddle">
          <div>
            <div className="">
              
              <div className="col s12" style={{transition: "opacity .2s ease-in-out"}}>
                <Card className="row" style={{marginBottom: 10}}>
                  <div className="flexSpaceBetween" style={{padding: 16,}}>
                    <CardTitle style={{padding: 0, fontSize: 22}} titleStyle={{fontSize: 22}}
                               title="ACCOUNT INFORMATION"
                               subtitle=""/>
                    <ToolbarGroup>
                      <RaisedButton
                        icon={<ModeEdit/>}
                        label="Update Profile"
                        onClick={this.handleOpenEdit}
                        primary={true}/>
                    </ToolbarGroup>
                  </div>
                </Card>
                <Card style={{marginBottom: 10}}>
                  <Toolbar className="toolbarCard" style={{backgroundColor: '#fff'}}>
                    <ToolbarGroup>
                      <ToolbarTitle
                        style={{fontSize: 14, fontWeight: 500, color: '#32325d', textTransform: 'capitalize'}}
                        text={'Details'}/>
                    </ToolbarGroup>
                  </Toolbar>
                  <Divider/>
                  <CardText>
                    <div className="row">
                      <div className="col s12 m4 l4">
                      {
                        (this.profileStore.userProfile.photo == null) ? 
                        <Dragger {...props}>
                          <p className="ant-upload-drag-icon">
                            <Icon type="inbox" />
                          </p>
                          <p className="ant-upload-text">Click or drag file to this area to upload</p>
                          <p className="ant-upload-hint">Change Your Photo Profile</p>
                        </Dragger> : 
                        <CardAntd
                            hoverable
                            style={{ width: 240 }}
                            cover={<img alt="example" src={this.http.appendImagePath(this.profileStore.userProfile.photo)} />}
                          >
                            <Meta
                              title={<Upload {...props}><Button><Icon type="upload"/>Change Picture</Button></Upload>}
                            />
                        </CardAntd>
                      }
                      
                      </div>
                      <div className="col s12 m8 l8">
                        <div className="listCustDetail">
                          <div className="listCustDetailItem flex">
                          </div>
                          <div className="listCustDetailItem flex">
                            <p className="listCustomerDetailItemKey">Name</p>
                            <p className="listCustomerDetailItemValue">{this.profileStore.userProfile.firstname} {this.profileStore.userProfile.lastname}</p>
                          </div>
                          <div className="listCustDetailItem flex">
                            <p className="listCustomerDetailItemKey">Place and Date of birth</p>
                            <p
                              className="listCustomerDetailItemValue">{this.profileStore.userProfile.place_of_birth}{this.profileStore.userProfile.place_of_birth ? ',': ''} {(this.profileStore.userProfile.date_of_birth == null) ? '' : moment(this.profileStore.userProfile.date_of_birth).format('DD MMMM YYYY')}</p>
                          </div>
                          <div className="listCustDetailItem flex">
                            <p className="listCustomerDetailItemKey">Gender</p>
                            <p
                              className="listCustomerDetailItemValue">{this.profileStore.userProfile.gender}</p>
                          </div>
                          {/*<div className="listCustDetailItem flex">*/}
                            {/*<p className="listCustomerDetailItemKey">Email</p>*/}
                            {/*<p className="listCustomerDetailItemValue"></p>*/}
                          {/*</div>*/}
                          <div className="listCustDetailItem flex">
                            <p className="listCustomerDetailItemKey">Phone Number</p>
                            <p className="listCustomerDetailItemValue">{this.profileStore.userProfile.phone}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </CardText>
                </Card>
              </div>
            </div>
            <Dialog
              modal={true}
              open={this.state.openedEditDialog}
              actions={actionsEdit}
            >
              <div style={{padding: 20}}>

                <div className="row">
                  <div className="col s12 m6 l6">
                    <p className="label-form">First Name</p>
                    <TextField
                      fullWidth={true}
                      onChange={this.handleChangeFirstName}
                      value={this.profileStore.userProfile.firstname}
                    />
                  </div>
                  <div className="col s12 m6 l6">
                    <p className="label-form">Last Name</p>
                    <TextField
                      fullWidth={true}
                      onChange={this.handleChangeLastName}
                      value={this.profileStore.userProfile.lastname}
                    />
                  </div>
                </div>

                <div className="row">
                  <div className="col s12 m6 l6">
                    <p className="label-form">Place of </p>
                    <TextField
                      fullWidth={true}
                      onChange={this.handleChangePlace}
                      value={this.profileStore.userProfile.place_of_birth}
                    />
                  </div>
                  <div className="col s12 m6 l6">
                    <p className="label-form">Date of Birth</p>
                    <DatePicker
                      hintText="Landscape Dialog"
                      mode="landscape"
                      openToYearSelection
                      onChange={this.handleChangeDate}
                      value={(this.profileStore.userProfile.date_of_birth == null) ? '' : moment(this.profileStore.userProfile.date_of_birth).toDate()}
                      formatDate={
                        new DateTimeFormat('en-US', {
                          year: 'numeric',
                          day: 'numeric',
                          month: 'numeric',

                        }).format
                      }
                    />
                  </div>
                </div>

                <div className="row">
                  <div className="col s12 m6 l6">
                    <p className="label-form">Phone</p>
                    <TextField
                      fullWidth={true}
                      onChange={this.handleChangePhone}
                      value={this.profileStore.userProfile.phone}
                    />
                  </div>
                  <div className="col s12 m6 l6">
                    <p className="label-form">Gender</p>
                    <SelectField
                      value={this.profileStore.userProfile.gender}
                      fullWidth={true}
                      onChange={this.handleChangeGender}
                    >
                      <MenuItem value={"male"} primaryText="Male" />
                      <MenuItem value={"female"} primaryText="Female" />
                    </SelectField>
                  </div>
                </div>
              </div>
            </Dialog>
          </div>
      </div>
    )
  }
}

export default Form.create()(GeneralInformation);
