import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
import {
  InputAdornment,
  TextField,
  Button,
  Fab,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  FormControl,
  TextareaAutosize,
  Paper,
  CardMedia,
  MenuItem,
  Snackbar,
} from "@material-ui/core";
import AccountCircle from "@material-ui/icons/AccountCircle";
import MailOutlineIcon from "@material-ui/icons/MailOutline";
import ContactPhoneIcon from "@material-ui/icons/ContactPhone";
import BusinessIcon from "@material-ui/icons/Business";
import EditIcon from "@material-ui/icons/Edit";
import { connect } from "react-redux";
import PhotoCameraIcon from "@material-ui/icons/PhotoCamera";
import Avatar from "react-avatar";
import AddAPhotoIcon from "@material-ui/icons/AddAPhoto";
import AddPhotoAlternateIcon from "@material-ui/icons/AddPhotoAlternate";
import axios from "axios";
const styles = (theme) => ({
  margin: {
    margin: theme.spacing(1),
  },
});

class Profile extends Component {
  state = {
    user: [],
    file: null,
    open: false,
    openupdate: false,
    edit: false,
  };
  handleClickOpen = () => {
    this.setState({
      open: true,
    });
  };
  handleClose = () => {
    this.setState({
      open: false,
    });
  };
  handleClickEdit = () => {
    this.setState({
      edit: true,
    });
  };
  handleCloseEdit = () => {
    this.setState({
      edit: false,
    });
  };
  handleClickOpenupdate = () => {
    this.setState({
      openupdate: true,
    });
  };
  handleCloseupdate = () => {
    this.setState({
      openupdate: false,
    });
  };
  handleChange = (event) => {
    let { user } = this.state;
    console.log("name : ", event.target.name);
    console.log("value : ", event.target.value);

    user[event.target.name] = event.target.value;

    this.setState({
      user,
    });
  };
  componentDidMount = async () => {
    const { location, userInfo } = this.props;
    // const id = userInfo.id;
    const response = await axios.get(
      `http://localhost:9000/api/auth/getUserById/${userInfo.id}`
    );

    console.log(userInfo);
    const resposeimguser = await axios.get(
      `http://localhost:9000/api/storageprofile/file/user/${userInfo.id}`
    );
    if(resposeimguser.data){
      response.data.image =
      "data:" + resposeimguser.data.type + ";base64," + resposeimguser.data.url;
      console.log(resposeimguser);
    }
      console.log(response.data);
  
   
   
 
    if (response.data)
      this.setState({
        user: response.data,
      });
  };
  render() {
    const { classes, userInfo } = this.props;
    const { user, file, shop, open, openupdate, edit } = this.state;
    return (
      <div className="row center">
        <div className="row mt-2 mb-2">
          <h2>โปรไฟล์</h2>
        </div>
        <br />
        <div className="row mt-2 mb-2">
          <div className="col s12 m12 l4">
            <div className="row center">
              <br />
              <Avatar
                skypeId="sitebase"
                src={user.image}
                size="200"
                round={true}
              />
            </div>

            <div className="row center">
              {user.image ? (
                <Button
                  variant="outlined"
                  onClick={this.handleClickOpenupdate}
                  color="primary"
                >
                  <PhotoCameraIcon />
                  แก้ไขรูปภาพร้าน
                </Button>
              ) : (
                <Button
                  variant="outlined"
                  color="primary"
                  onClick={this.handleClickOpen}
                >
                  <AddAPhotoIcon />
                  เพิ่มรูปภาพร้าน
                </Button>
              )}

              <Dialog
                open={open}
                onClose={this.handleClose}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
              >
                <DialogTitle id="alert-dialog-title">
                  {"เพิ่มรูปภาพ"}
                </DialogTitle>
                <DialogContent>
                  <TextField
                    className={classes.margin}
                    id="outlined-file-input"
                    label="เพิ่มรูปภาพ"
                    type="file"
                    autoComplete="current-password"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AddPhotoAlternateIcon />
                        </InputAdornment>
                      ),
                    }}
                    onChange={(e) => {
                      this.setState({
                        file: e.target.files[0],
                      });
                    }}
                  />
                </DialogContent>
                <DialogActions>
                  <Button onClick={this.handleClose} color="primary">
                    ยกเลิก
                  </Button>
                  <Button
                    onClick={() => {
                      const { location, userInfo } = this.props;
                      const formData = new FormData();
                      console.log(file);

                      formData.append("images", file);
                      // formData.append("shop_id", shop.id);
                      formData.append("userId", userInfo.id);

                      axios
                        .post(
                          `http://localhost:9000/api/storageprofile/upload/user/${userInfo.id}`,
                          formData
                        )
                        .then((response) => {
                          console.log("เพิ่มรูปภาพสำเร็จ", response);
                          alert("เพิ่มรูปภาพสำเร็จ");
                          this.handleClose();
                        })
                        .catch((error) => {
                          console.log(error);
                        });
                    }}
                    color="primary"
                    autoFocus
                  >
                    ยืนยัน
                  </Button>
                </DialogActions>
              </Dialog>

              <Dialog
                open={openupdate}
                onClose={this.handleCloseupdate}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
              >
                <DialogTitle id="alert-dialog-title">
                  {"แก้ไขรูปภาพ"}
                </DialogTitle>
                <DialogContent>
                  <TextField
                    className={classes.margin}
                    id="outlined-file-input"
                    label="แก้ไขรูปภาพ"
                    type="file"
                    autoComplete="current-password"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <AddPhotoAlternateIcon />
                        </InputAdornment>
                      ),
                    }}
                    onChange={(e) => {
                      this.setState({
                        file: e.target.files[0],
                      });
                    }}
                  />
                </DialogContent>
                <DialogActions>
                  <Button onClick={this.handleCloseupdate} color="primary">
                    ยกเลิก
                  </Button>
                  <Button
                    onClick={() => {
                      const { location, userInfo } = this.props;
                      const formData = new FormData();
                      console.log(file);

                      formData.append("images", file);
                      // formData.append("shop_id", shop.id);
                      formData.append("userId", userInfo.id);

                      axios
                        .put(
                          `http://localhost:9000/api/storageprofile/file/user/${userInfo.id}`,
                          formData
                        )
                        .then((response) => {
                          console.log("แก้ไขรรูปภาพสำเร็จ", response);
                          alert("แกไขรูปภาพสำเร็จ");
                          this.handleCloseupdate();
                        })
                        .catch((error) => {
                          console.log(error);
                        });
                    }}
                    color="primary"
                    autoFocus
                  >
                    ยืนยัน
                  </Button>
                </DialogActions>
              </Dialog>
            </div>
          </div>
          <div className="col s12 m12 l8">
            <div ClassName="row mt-5">
              <TextField
                className={classes.margin}
                id="name"
                name="name"
                value={user.name}
                label="ชื่อ-นามสกุล"
                variant="outlined"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <AccountCircle />
                    </InputAdornment>
                  ),
                }}
              />

              <TextField
                className={classes.margin}
                id="email"
                name="email"
                value={user.email}
                label="E_mail"
                variant="outlined"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <MailOutlineIcon />
                    </InputAdornment>
                  ),
                }}
              />
            </div>
            <br></br>
            <div>
              <TextField
                className={classes.margin}
                id="address"
                name="address"
                value={user.address}
                label="ที่อยู่"
                autoComplete="address"
                variant="outlined"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <BusinessIcon />
                    </InputAdornment>
                  ),
                }}
              />

              <TextField
                className={classes.margin}
                id="tel"
                name="tel"
                value={user.tel}
                label="เบอร์โทร"
                autoComplete="Phone number"
                variant="outlined"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <ContactPhoneIcon />
                    </InputAdornment>
                  ),
                }}
              />
            </div>

            {/* <div className="row mt-5">
              <div className={classes.root}>
                <Fab
                  color="secondary"
                  aria-label="edit"
                  onClick={this.handleClickEdit}
                >
                  <EditIcon />
                </Fab>
                <Dialog
                  open={edit}
                  onClose={this.handleCloseEdit}
                  aria-labelledby="alert-dialog-title"
                  aria-describedby="alert-dialog-description"
                >
                  <DialogTitle id="alert-dialog-title">
                    {"แก้ไขข้อมูลโปรไฟล์"}
                  </DialogTitle>
                  <DialogContent>
                    <div ClassName="row">
                      <TextField
                        className={classes.margin}
                        id="name"
                        name="name"
                        value={user.name}
                        label="ชื่อ-นามสกุล"
                        variant="outlined"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <AccountCircle />
                            </InputAdornment>
                          ),
                        }}
                        onChange={this.handleChange}
                      />

                      <TextField
                        className={classes.margin}
                        id="email"
                        name="email"
                        value={user.email}
                        label="E_mail"
                        variant="outlined"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <MailOutlineIcon />
                            </InputAdornment>
                          ),
                        }}
                        onChange={this.handleChange}
                      />
                    
                      <TextField
                        className={classes.margin}
                        id="address"
                        name="address"
                        value={user.address}
                        label="ที่อยู่"
                        autoComplete="address"
                        variant="outlined"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <BusinessIcon />
                            </InputAdornment>
                          ),
                        }}
                        onChange={this.handleChange}
                      />

                      <TextField
                        className={classes.margin}
                        id="tel"
                        name="tel"
                        value={user.tel}
                        label="เบอร์โทร"
                        autoComplete="Phone number"
                        variant="outlined"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <ContactPhoneIcon />
                            </InputAdornment>
                          ),
                        }}
                        onChange={this.handleChange}
                      />
                    </div>
                  </DialogContent>
                  <DialogActions>
                    <Button
                      variant="contained"
                      color="secondary"
                      onClick={this.handleCloseEdit}
                    >
                      ยกเลิก
                    </Button>{" "}
                    &nbsp; &nbsp; &nbsp;
                    <Button
                      variant="contained"
                      color="primary"
                      onClick={() => {
                        axios
                          .put("http://localhost:9000/api/auth/updateProfile/:id", {
                            ...user,
                
                          })
                          .then((response) => {
                            console.log("แก้ไขข้อมูลสำเร็จ", response);
                            alert("แก้ไขข้อมูลสำเร็จ");
                            this.handleCloseEdit();
                          })
                          .catch((error) => {
                            console.log(error);
                          });
                      }}
                    >
                      ตกลง
                    </Button>
                  </DialogActions>
                </Dialog> */}
            {/* </div>
            </div> */}
          </div>
        </div>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  userInfo: state.user,
});

const mapDispatchToProps = (dispatch) => {};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(compose(withStyles(styles), withRouter)(Profile));
