import React, { Component } from "react";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import {
  Dialog,
  Button,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  InputAdornment,
} from "@material-ui/core";

import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
import Fab from "@material-ui/core/Fab";
import AddIcon from "@material-ui/icons/Add";
import AddPhotoAlternateIcon from "@material-ui/icons/AddPhotoAlternate";
import MaterialTable from "material-table";
import axios from "axios";
import { connect } from "react-redux";
const styles = (theme) => ({
  root: {
    height: 150,
    flexGrow: 1,
    transform: "translateZ(0)",
    // The position fixed scoping doesn't work in IE 11.
    // Disable this demo to preserve the others.
    "@media all and (-ms-high-contrast: none)": {
      display: "none",
    },
  },
  modal: {
    display: "flex",
    padding: theme.spacing(1),
    alignItems: "center",
    justifyContent: "center",
  },
  fab: {
    position: "absolute",
    bottom: theme.spacing(2),
    right: theme.spacing(2),
  },
});

class AddImage extends Component {
  state = {
    open: false,
    columns: [{ title: "รูปภาพ", field: "img" }],
    data: [],
    file: null,
    shop: [],
  };
  handleClickOpen = () => {
    this.setState({
      open: true,
    });
  };
  handleClose = () => {
    this.setState({
      open: false,
    });
  };
  handleCloseAndSave = () => {
    //Save to db

    this.setState((prevState) => {
      const data = [...prevState.data];
      const newData = {
        img: "Mehmet",
      };
      data.push(newData);
      return { ...prevState, data: data, open: false };
    });

    // this.setState({
    //   open: false
    // });
  };
  // componentDidMount = () => {
  //   let { pathname } = this.props.location;
  //   pathname = pathname.substring(1, pathname.length);
  //   // console.log('pathname', pathname)
  // };

  componentDidMount = async () => {
    const { location, userInfo } = this.props;
    const { shop } = this.state;
    // const id = location.state.id;
    // const response = await axios.get(
    //   `http://localhost:9000/api/shop/getUserId/${userInfo.id}`
    // );
    // console.log("response.data", response.data);
    // if (response.data)
    //   this.setState({
    //     shop: response.data,
    //     data: response.data,
    //   });
    const response = await axios.get(
      `http://localhost:9000/api/shop/getUserId/${userInfo.id}`
    );
    const resposeimgshop = await axios.get(`http://localhost:9000/api/storage/file/shop/${response.data.id}`)
    // console.log(resposeimgshop);
    
    response.data.image = ('data:' + resposeimgshop.data.type+';base64,'+resposeimgshop.data.url)
    console.log("response.data",response.data);
    // console.log("response.data",b.data);
    if (response.data)
      this.setState({
        shop: response.data,
        data: response.data
      });
    // if (b.data)
    //   this.setState({
      
    //     data: b.data,
    //   });
  };

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

    const { open, columns, data, file, shop } = this.state;
    return (
      <div>
        <MaterialTable
          title="รูปภาพร้าน"
          columns={columns}
          data={data}
          options={{
            selection: false,
          }}
          editable={{
            onRowDelete: (oldData) =>
              new Promise((resolve) => {
                setTimeout(() => {
                  resolve();
                  this.setState((prevState) => {
                    const data = [...prevState.data];
                    data.splice(data.indexOf(oldData), 1);
                    return { ...prevState, data };
                  });
                }, 600);
              }),
          }}
        />
        <div className="row">
          <Fab
            aria-label={"add"}
            className={classes.fab}
            color="primary"
            onClick={this.handleClickOpen}
          >
            <AddIcon />
          </Fab>

          <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"
                variant="outlined"
                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/storageshop/upload/work/${shop.id}`,
                      formData
                    )
                    .then((response) => {
                      console.log("เพิ่มรูปภาพสำเร็จ", response);
                      alert("เพิ่มรูปภาพสำเร็จ");
                      this.handleClose();
                    })
                    .catch((error) => {
                      console.log(error);
                    });
                }}
                color="primary"
                autoFocus
              >
                ยืนยัน
              </Button>
            </DialogActions>
          </Dialog>
        </div>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  userInfo: state.user,
});

const mapDispatchToProps = (dispatch) => {};

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