import React from 'react';
import withStyles from "@material-ui/core/styles/withStyles";
import { styles } from './styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import Button from '@material-ui/core/Button';
import Hidden from '@material-ui/core/Hidden';
import InputAdornment from '@material-ui/core/InputAdornment';
import IconButton from '@material-ui/core/IconButton';
import CircularProgress from '@material-ui/core/CircularProgress';
import Snackbar from '@material-ui/core/Snackbar';

import { Link } from 'react-router-dom'
import { inject, observer } from "mobx-react";
import schema from 'async-validator'
import { startCase } from 'lodash';
import { Upload, Icon, message } from 'antd';

import AutoComplete from './../../components/AutoComplete';
import {appConfig} from "../../config/app";
import {LINKS} from "../../routes";

// const province = require("./../../../../assets/data/province.json");
// const city = require("./../../../../assets/data/city.json");
// const district = require("./../../../../assets/data/district.json");
// const subdistrict = require("./../../../../assets/data/subdistrict.json");

@inject('appstate')
@observer
class RegisterPage extends React.Component {
    state = {
        showPassword: false,
        showConfirmPassword: false,
        openDialog: false,
        isLoading: false,

        fileList_ktp: [],
        fileList_photo: [],

        query: {},
        errors: {
          email_exists: '',
          phone_exists: '',
          referal_not_found: '',
          no_ktp: '',
          no_rekening: ''
        },

        // form
        confirmPassword: "",
        phone_number: "",
        email: "",
        password: "",
        full_name: "",
        no_ktp: '',
        no_rekening: '',
        upload_ktp: '',
        upload_photo: '',
        address: '',
        province: '',
        city: '',
        district: '',
        sub_district: '',
        zip_code: '',
    };

    constructor(props) {
        super(props);
        this.authStore = props.appstate.auth;
        this.http = props.appstate.http;
        this.place = props.appstate.places;
    }

    componentDidMount() {
      let {location:{search}} = this.props;
      search = search.substr(1);

      const query = search.split("&")
        .map(q => q.split('='))
        .reduce((all, q) => {
          all[q[0]] = q[1];
          return all;
        }, {});

      this.setState({query});

      this.place.getAllProvince();
    }

    onChangeProvince = (value) => {
      this.setState({
        province: value
      });
      this.place.getCitiesByProvince(value);
    };

    onChangeCity = (value) => {
      this.setState({
        city: value
      });
      this.place.getDistrictByCity(value);
    };

    onChangeDistrict = (value) => {
      this.setState({
        district: value
      });
      this.place.getSubdistrictByDistrict(value);
    };

    onChangeSubdistrict = (value) => {
      this.setState({
        subdistrict: value
      });
    };

    handleChange = name => event => {
        if((name === 'no_ktp' || name === 'no_rekening') && (this.state.errors.no_ktp !== '' && this.state.errors.no_rekening !== '')){
            this.setState({
                errors:{
                    ...this.state.errors,
                    no_ktp: '',
                    no_rekening: ''
                }
            });
        }

      {console.log("namee", name)}
        this.setState({
            [name]: event.target.value,
        });
    };

    viewPassword = () => {
        this.setState({
            showPassword: !this.state.showPassword
        })
    };

    viewConfirmPassword = () => {
        this.setState({
            showConfirmPassword: !this.state.showConfirmPassword
        })
    };

    register = () => {

        // return this.props.history.push(LINKS.LOGIN);

        // if (this.state.password.length < 8) {
        //   return message.warning("password need atleast 8 characters");
        // }

       // if (this.state.upload_photo === '') {
        //  return message.warning("please upload photo");
        //}
//

        if (this.state.phone_number === '') {
          return this.setState({
            errors: {
              ...this.state.errors,
              phone_exists: 'Harap isi nomor handphone anda'
            }
          })
        }

        if (this.state.email === '') {
         return this.setState({
           errors: {
             ...this.state.errors,
             email_exists: 'Harap isi email anda'
           }
         })
        }

        if(this.state.no_ktp === '' && this.state.no_rekening === ''){
            return this.setState({
                errors: {
                  ...this.state.errors,
                  no_ktp: 'Salah satu harus diisi',
                  no_rekening: 'Salah satu harus diisi'
                }
              })
        }

        this.setState({ isLoading: true });

        let data = {
            fullname: this.state.full_name,
            email: this.state.email,
            phone_number: this.state.phone_number,
            password: this.state.password,
            nric_number: this.state.no_ktp,
            // nric_photo_path: this.state.upload_ktp,
            // photo: this.state.upload_photo,
            // address: this.state.address,
            // province_id: this.state.province,
            // city_id: this.state.city,
            // district_id: this.state.district,
            // subdistrict_id: this.state.subdistrict,
            // zip_code: this.state.zip_code,
            referal: this.state.query.referal,
            additional_data: {
                no_rekening : this.state.no_rekening
            }
        };
        this.props.history.push(LINKS.VOUCHERS);
        // this.authStore.register(data).then(res => {
        //     //message.success("Please check your email to confirm your account");this.props.history.push(LINKS.LOGIN);
        //     setTimeout(() => {
        //         this.setState({ isLoading: false });
        //       this.props.history.push(LINKS.REGISTER_COMPLETED);
        //     //     this.props.history.push(LINKS.LOGIN);
        //     }, 250);
        // }).catch(err => {
        //     this.setState({ isLoading: false });
        //
        //     if (err.type === 'BodyValidationError') {
        //       message.error(err.detail[0].message);
        //     } else {
        //       if (err.message.toLowerCase().includes('email')) {
        //         this.setState({
        //           errors: {
        //             ...this.state.errors,
        //             email_exists: 'Email sudah terdaftar'
        //           }
        //         })
        //       } else if (err.message.toLowerCase().includes('phone number')) {
        //         this.setState({
        //           errors: {
        //             ...this.state.errors,
        //             phone_exists: 'Nomer handphone sudah terdaftar'
        //           }
        //         })
        //       } else if (err.message.toLowerCase().includes('referal')) {
        //         this.setState({
        //           errors: {
        //             ...this.state.errors,
        //             referal_not_found: 'Kode Referal Salah - Silahkan Hubungi Petugas BTN'
        //           }
        //         })
        //       } else {
        //         message.error(err.message);
        //       }
        //     }
        // });
    };

    handleChangeUploadKtp = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                upload_ktp,
                loading: false,
            }));
        }
    };

    handleChangeUploadPhoto = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                upload_photo,
                loading: false,
            }));
        }
    };

    uploadOnChange = (key, info) => {
        let fileList = info.fileList;

        this.setState({
          [`fileList_${key}`]: fileList
        })
    };

    createUploadProps = (key) => {
      return {
        name: 'file',
        multiple: false,
        action: appConfig.apiUrl + 'upload',
        customRequest: ({file, onProgress, onSuccess}) => {
          this.setState({
            uploading: true
          });
          this.http.upload(file)
            .then(res => {
              this.setState({
                [`upload_${key}`]: appConfig.apiUrl + res.path.slice(1,res.path.length)
              });
              return res;
            })
            .then(res => {
              message.success(`${file.name} file uploaded successfully.`);

              const fileList = this.state[`fileList_${key}`];

              console.log(key, fileList, this.state);

              const selectedIndex = fileList.findIndex(f => f.name === file.name);

              fileList[selectedIndex].status = "done";
              fileList[selectedIndex].path = res.path;
              onSuccess(fileList[selectedIndex]);
              // form.setFieldsValue({path: res.path});

              this.setState({
                uploading: false,
                // fileList: []
                [`fileList_${key}`]: [fileList[selectedIndex]]
              });
            });

          return {
            abort: () => {}
          }
        },
        fileList: this.state[`fileList_${key}`],
        onChange: (info) => this.uploadOnChange(key, info),
        onRemove: file => true
      };
    };

    render() {
        const { classes } = this.props;

        const uploadButtonKtp = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload KTP</div>
            </div>
        );

        const uploadButtonPhoto = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload Photo</div>
            </div>
        );

        const upload_ktp = this.state.upload_ktp;
        const upload_photo = this.state.upload_photo;

        return (
            <div className={classes.container}>
                {/*<AlertSuccess open={appStore.global_ui.openSuccess} onClose={()=>appStore.global_ui.closeAlertSuccess()}/>*/}

                <Grid container spacing={0} className={classes.gridContainer}>
                    <Grid item cols={12} className={classes.logoContainer}>
                        <img src={require('../../../../assets/images/kb_bukopin.jpeg')} className={classes.logo} />
                    </Grid>
                    <Grid item xs={12} sm={12} md={10} lg={10} className={classes.registerContainer} style={{
                      alignSelf: 'center'
                    }}>
                        <Grid container spacing={24} className={classes.registerPaper}>
                            <Hidden smDown>
                                <Grid item xs={5}>
                                    <img src={require('../../../../assets/images/register_image_2.png')} width={"80%"} />
                                    <Typography style={{ color: '#FFF' }} variant={"h6"}>
                                        Selamat Datang di Bukopin Shop!
                                    </Typography>
                                    <Typography style={{ color: '#FFF' }} variant={"subtitle2"}>
                                        Dapatkan promo dan keuntungan lebih dari Bukopin!
                                    </Typography>
                                </Grid>
                            </Hidden>
                            <Grid item xs={12} sm={12} md={7} style={{ paddingLeft: 50, paddingRight: 50 }}>
                                <Paper className={classes.formRegister}>
                                    <Typography variant="h6" gutterBottom>
                                        Daftar Sekarang
                                    </Typography>
                                    {/*<Typography variant="subtitle2" gutterBottom>*/}
                                        {/*Already have an account? <Link to={"/login"} replace>Back to Login</Link>*/}
                                    {/*</Typography>*/}
                                    <div style={{
                                        display: 'flex',
                                        flexDirection: 'row'
                                    }}>
                                        <Grid container spacing={16}>
                                            <Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 7, paddingRight: 5 }}>
                                                <TextField
                                                    id="name"
                                                    label="Nama Lengkap"
                                                    value={this.state.full_name}
                                                    onChange={this.handleChange('full_name')}
                                                    margin="normal"
                                                    type={"text"}
                                                    variant="outlined"
                                                    fullWidth
                                                />
                                            </Grid>
                                            <Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 7 }}>
                                                <TextField
                                                    id="phone"
                                                    label="Nomor Handphone"
                                                    value={this.state.phone_number}
                                                    onChange={this.handleChange('phone_number')}
                                                    margin="normal"
                                                    type={"number"}
                                                    variant="outlined"
                                                    fullWidth
                                                    error={!!this.state.errors.phone_exists}
                                                    helperText={this.state.errors.phone_exists}
                                                />
                                            </Grid>

                                            <Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 7, paddingRight: 5 }}>
                                                <TextField
                                                    id="email"
                                                    label="Email"
                                                    value={this.state.email}
                                                    onChange={this.handleChange('email')}
                                                    margin="normal"
                                                    variant="outlined"
                                                    fullWidth
                                                    error={!!this.state.errors.email_exists}
                                                    helperText={this.state.errors.email_exists}
                                                />
                                            </Grid>
                                            <Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 7 }}>
                                                <TextField
                                                    id="ktp"
                                                    label="Nomor KTP"
                                                    value={this.state.no_ktp}
                                                    onChange={this.handleChange('no_ktp')}
                                                    margin="normal"
                                                    type={"number"}
                                                    variant="outlined"
                                                    fullWidth
                                                    error={!!this.state.errors.no_ktp}
                                                    helperText={this.state.errors.no_ktp}
                                                />
                                            </Grid>

                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5,paddingTop:16 }}>*/}
                                                {/*<Upload*/}
                                                    {/*name="avatar"*/}
                                                    {/*listType="picture-card"*/}
                                                    {/*className="avatar-uploader"*/}
                                                    {/*showUploadList={false}*/}
                                                    {/*{...this.createUploadProps("ktp")}*/}
                                                {/*>*/}
                                                    {/*{upload_ktp ? <img src={upload_ktp} alt="avatar" style={{*/}
                                                      {/*width: 104,*/}
                                                      {/*height: 104*/}
                                                    {/*}}/> : uploadButtonKtp}*/}
                                                {/*</Upload>*/}
                                            {/*</Grid>*/}
                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5, paddingTop:16 }}>*/}
                                                {/*<Upload*/}
                                                    {/*style={{ marginTop: 16, marginBottom: 8 }}*/}
                                                    {/*name="avatar"*/}
                                                    {/*listType="picture-card"*/}
                                                    {/*className="avatar-uploader"*/}
                                                    {/*showUploadList={false}*/}
                                                    {/*{...this.createUploadProps("photo")}*/}
                                                {/*>*/}
                                                    {/*{upload_photo ? <img src={upload_photo} alt="avatar" style={{*/}
                                                      {/*width: 104,*/}
                                                      {/*height: 104*/}
                                                    {/*}}/> : uploadButtonPhoto}*/}
                                                {/*</Upload>*/}
                                            {/*</Grid>*/}

                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<TextField*/}
                                                    {/*id="address"*/}
                                                    {/*label="Address"*/}
                                                    {/*value={this.state.address}*/}
                                                    {/*onChange={this.handleChange('address')}*/}
                                                    {/*margin="normal"*/}
                                                    {/*variant="outlined"*/}
                                                    {/*fullWidth*/}
                                                {/*/>*/}
                                            {/*</Grid>*/}
                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<AutoComplete*/}
                                                  {/*placeholder={"Province"}*/}
                                                  {/*onChange={({value}) => this.onChangeProvince(value)}*/}
                                                  {/*suggestions={this.place.provinces.map(p => {*/}

                                                    {/*return {*/}
                                                      {/*label: p.name,*/}
                                                      {/*value: p.id*/}
                                                    {/*}*/}
                                                  {/*})}/>*/}
                                            {/*</Grid>*/}

                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<AutoComplete*/}
                                                  {/*placeholder={"City"}*/}
                                                  {/*onChange={({value}) => this.onChangeCity(value)}*/}
                                                  {/*suggestions={this.place.cities.map(p => {*/}

                                                    {/*return {*/}
                                                      {/*label: p.name,*/}
                                                      {/*value: p.id*/}
                                                    {/*}*/}
                                                  {/*})}/>*/}
                                            {/*</Grid>*/}
                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<AutoComplete*/}
                                                  {/*placeholder={"District"}*/}
                                                  {/*onChange={({value}) => this.onChangeDistrict(value)}*/}
                                                  {/*suggestions={this.place.districts.map(p => {*/}

                                                    {/*return {*/}
                                                      {/*label: p.name,*/}
                                                      {/*value: p.id*/}
                                                    {/*}*/}
                                                  {/*})}/>*/}
                                            {/*</Grid>*/}

                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<AutoComplete*/}
                                                  {/*placeholder={"Subdistrict"}*/}
                                                  {/*onChange={({value}) => this.onChangeSubdistrict(value)}*/}
                                                  {/*suggestions={this.place.subdistricts.map(p => {*/}

                                                    {/*return {*/}
                                                      {/*label: p.name,*/}
                                                      {/*value: p.id*/}
                                                    {/*}*/}
                                                  {/*})}/>*/}
                                            {/*</Grid>*/}
                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<TextField*/}
                                                    {/*id="zip_code"*/}
                                                    {/*label="Zip Code"*/}
                                                    {/*value={this.state.zip_code}*/}
                                                    {/*onChange={this.handleChange('zip_code')}*/}
                                                    {/*margin="normal"*/}
                                                    {/*variant="outlined"*/}
                                                    {/*fullWidth*/}
                                                {/*/>*/}
                                            {/*</Grid>*/}

                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<TextField*/}
                                                    {/*id="password"*/}
                                                    {/*label="Password"*/}
                                                    {/*value={this.state.password}*/}
                                                    {/*onChange={this.handleChange('password')}*/}
                                                    {/*margin="normal"*/}
                                                    {/*type={this.state.showPassword ? 'text' : 'password'}*/}
                                                    {/*variant="outlined"*/}
                                                    {/*fullWidth*/}
                                                    {/*InputProps={{*/}
                                                        {/*endAdornment: (*/}
                                                            {/*<InputAdornment position="end">*/}
                                                                {/*<IconButton*/}
                                                                    {/*aria-label="Toggle password visibility"*/}
                                                                    {/*onClick={this.viewPassword}*/}
                                                                {/*>*/}
                                                                    {/*{this.state.showPassword ? <VisibilityOff /> : <Visibility />}*/}
                                                                {/*</IconButton>*/}
                                                            {/*</InputAdornment>*/}
                                                        {/*),*/}
                                                    {/*}}*/}
                                                {/*/>*/}
                                            {/*</Grid>*/}
                                            {/*<Grid item xs={12} sm={12} md={6} style={{ paddingLeft: 5, paddingRight: 5 }}>*/}
                                                {/*<TextField*/}
                                                    {/*id="confirmPassword"*/}
                                                    {/*label="Re-type Password"*/}
                                                    {/*value={this.state.confirmPassword}*/}
                                                    {/*onChange={this.handleChange('confirmPassword')}*/}
                                                    {/*margin="normal"*/}
                                                    {/*type={this.state.showConfirmPassword ? 'text' : 'password'}*/}
                                                    {/*fullWidth*/}
                                                    {/*variant="outlined"*/}
                                                    {/*InputProps={{*/}
                                                        {/*endAdornment: (*/}
                                                            {/*<InputAdornment position="end">*/}
                                                                {/*<IconButton*/}
                                                                    {/*aria-label="Toggle password visibility"*/}
                                                                    {/*onClick={this.viewConfirmPassword}*/}
                                                                {/*>*/}
                                                                    {/*{this.state.showConfirmPassword ? <VisibilityOff style={{ color: this.state.password == '' ? this.state.confirmPassword == '' : this.state.password != this.state.confirmPassword ? 'red' : 'green' }} /> : <Visibility style={{ color: this.state.password == '' ? this.state.confirmPassword == '' : this.state.password != this.state.confirmPassword ? 'red' : 'green' }} />}*/}
                                                                {/*</IconButton>*/}
                                                            {/*</InputAdornment>*/}
                                                        {/*),*/}
                                                    {/*}}*/}
                                                {/*/>*/}
                                            {/*</Grid>*/}
                                        </Grid>
                                    </div>
                                    <Grid item xs={12} sm={12} md={12}>
                                      <TextField
                                        label="Nomor Rekening"
                                        value={this.state.no_rekening}
                                        onChange={this.handleChange('no_rekening')}
                                        margin="normal"
                                        type={"number"}
                                        fullWidth
                                        error={!!this.state.errors.no_rekening}
                                        helperText={this.state.errors.no_rekening}
                                        variant="outlined"
                                      />
                                    </Grid>

                                    <Grid item xs={12} sm={12} md={12}>
                                      <TextField
                                        label="Kode Referal"
                                        value={this.state.query.referal}
                                        onChange={event => {
                                          this.setState({
                                            query: {
                                              ...this.state.query,
                                              referal: event.target.value
                                            }
                                          })
                                        }}
                                        margin="normal"
                                        type={"password"}
                                        fullWidth
                                        error={!!this.state.errors.referal_not_found}
                                        helperText={this.state.errors.referal_not_found || 'Hubungi petugas untuk mendapatkan hadiah'}
                                        variant="outlined"
                                      />
                                    </Grid>

                                    <div style={{ padding: 5, marginTop: 20 }}>
                                        <Button
                                          fullWidth
                                          variant="contained" style={{ backgroundColor: '#FAAF03' }} onClick={this.register}>
                                            {this.state.isLoading ? <CircularProgress className={classes.progress} /> : "Daftar"}
                                        </Button>

                                      <Typography variant="subtitle2" gutterBottom style={{
                                        marginTop: 16
                                      }}>
                                      Belum menerima email? <Link to={"/resend_email"} replace>Kirim ulang email</Link>
                                      </Typography>

                                      <Typography variant="subtitle2" gutterBottom>
                                        Belum menerima OTP? <Link to={"/resend_otp"} replace>Kirim ulang OTP</Link>
                                      </Typography>
                                    </div>
                                </Paper>
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>
            </div>
        )
    }
}

export default withStyles(styles)(RegisterPage);
