import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import {
  Dialog,
  Button,
  DialogActions,
  DialogContent,
  DialogTitle,
  InputAdornment,
  TextField,
  Fab,
} from "@material-ui/core";
import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
import AddIcon from "@material-ui/icons/Add";
import AccountCircle from "@material-ui/icons/AccountCircle";
import MailOutlineIcon from "@material-ui/icons/MailOutline";
import VpnKeyIcon from "@material-ui/icons/VpnKey";
import ContactPhoneIcon from "@material-ui/icons/ContactPhone";
import BusinessIcon from "@material-ui/icons/Business";

import MaterialTable from "material-table";

import { connect } from "react-redux";
import axios from "axios";

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),
  },
  table: {
    minWidth: 700,
  },
});

class Databeautician extends Component {
  state = {
    open: false,
    columns: [
      { title: "Name", field: "name" },
      { title: "E-mail", field: "email" },
      { title: "Address", field: "address" },
      {title: "Phone number", field: "tel",}
    ],
    data: [],

    name: "",
    email: "",
    password: "",
    password2: "",
    address: "",
    tel: "",
    rolr: "",
    shops: [],
  };
  handleChange = (event) => {
    console.log("name : ", event.target.name);
    console.log("value : ", event.target.value);

    this.setState({
      [event.target.name]: event.target.value,
    });
  };
  handleClickOpen = () => {
    this.setState({
      open: true,
    });
  };
  handleClose = () => {
    this.setState({
      open: false,
    });
  };
  handleCloseAndSave = () => {
    this.setState((prevState) => {
      const data = [...prevState.data];
      const newData = {
        name: "Mehmet",
        surname: "Baran",
        birthYear: 1987,
        birthCity: 63,
      };
      data.push(newData);
      return { ...prevState, data: data, open: false };
    });

    // this.setState({
    //   open: false
    // });
  };
  componentDidMount = async () => {
    const { location, userInfo } = this.props;
    const { shops } = this.state;

    const response = await axios.get(
      `http://localhost:9000/api/shop/getUserId/${userInfo.id}`
    );
    const responsedata = await axios.get(
      `http://localhost:9000/api/beautician/getbeauticianShopId/${shops.id}`
    );
    console.log(response.data);
    console.log(responsedata.data);
    this.setState({
      shops: response.data,
      data: responsedata.data 
    });
  };

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

    const {
      open,
      columns,
      data,
      name,
      email,
      password,
      password2,
      address,
      tel,
      shops,

      role,
    } = 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>
              <div>
                <TextField
                  className={classes.margin}
                  id="name"
                  name="name"
                  value={name}
                  label="ชื่อ-สกุล*"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <AccountCircle />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
              <br></br>
              <div>
                <TextField
                  className={classes.margin}
                  id="email"
                  name="email"
                  value={email}
                  label="E_mail*"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <MailOutlineIcon />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
              <br></br>
              <div>
                <TextField
                  className={classes.margin}
                  id="password"
                  name="password"
                  value={password}
                  label="Password*"
                  type="password"
                  autoComplete="current-password"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <VpnKeyIcon />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
              <br></br>
              <div>
                <TextField
                  className={classes.margin}
                  id="password2"
                  name="password2"
                  value={password2}
                  label="Confirm-Password*"
                  type="password"
                  autoComplete="current-password"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <VpnKeyIcon />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
              <br></br>
              <div>
                <TextField
                  className={classes.margin}
                  id="address"
                  name="address"
                  value={address}
                  label="ที่อยู่"
                  autoComplete="address"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <BusinessIcon />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
              <br></br>
              <div>
                <TextField
                  className={classes.margin}
                  id="tel"
                  name="tel"
                  value={tel}
                  label="เบอร์โทร"
                  autoComplete="Phone number"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <ContactPhoneIcon />
                      </InputAdornment>
                    ),
                  }}
                  onChange={this.handleChange}
                />
              </div>
            </DialogContent>
            <DialogActions>
              <Button onClick={this.handleClose} color="primary">
                ยกเลิก
              </Button>
              <Button
                color="primary"
                autoFocus
                onClick={() => {
                  if (password === password2) {
                    const register = axios.post(
                      "http://localhost:9000/api/auth/register",
                      {
                        name: name,
                        email: email,
                        password: password,
                        address: address,
                        tel: tel,
                        role: "2",
                      }
                    );
                    const Beautician = axios
                      .post("http://localhost:9000/api/beautician/add", {
                        name: name,
                        email: email,
                        address: address,
                        tel: tel,
                        shopID: shops.id,
                      })
                      .then((response) => {
                        console.log("สร้างผู้ใช้สำเร็จ", response);
                        this.handleClose();
                      })
                      .catch((error) => {
                        console.log(error);
                      });
                    // alert("ลงทะเบียนสำเร็จ");
                  } else {
                    alert("password ไม่ถูกต้อง");
                  }
                }}
              >
                ยืนยัน
              </Button>
            </DialogActions>
          </Dialog>
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  userInfo: state.user,
});

const mapDispatchToProps = (dispatch) => {};

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