import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
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 List extends Component {
  state = {
    columns: [
      { title: "ชื่อรายการ", field: "name" },
      { title: "ราคา", field: "price" },

      { title: "เวลาที่จอง", field: "time" },
    ],
    data: [],
    userId: null,
    lists: {
      id:"",
      name:"",
      price:"",
      time:""
    },
  };

  handleCloseAndSave = () => {
    //Save to db

    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 () => {
    let { pathname} = this.props.location;
    const { userInfo  } = this.props;
    pathname = pathname.substring(1, pathname.length);
    const { shop } = this.state;
  
    const responseshop = await axios.get(
      `http://localhost:9000/api/shop/getUserId/${userInfo.id}`
    );
   
    const response = await axios.get(
      `http://localhost:9000/api/list/getListshop/${responseshop.data.id}`
    );
    console.log("response.data", response.data);
    console.log("response.data", responseshop.data);


      this.setState({
        shop: responseshop.data,
        data: response.data,
        list: response.data,
      });
   
    

    // console.log('pathname', pathname)
  };

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

    const { columns, data, shop, userId, lists } = this.state;
    return (
      <div>
        <div className="row">
          <MaterialTable
            title="รายการ"
            columns={columns}
            data={data}
            options={{
              selection: false,
            }}
            editable={{
              onRowAdd: (newData) =>
                new Promise((resolve) => {
              
                  newData = { ...newData, shop: shop.id, userId: shop.userId };

                  axios
                    .post(`http://localhost:9000/api/list/add/`, newData)
                    .then((response) => {
                      console.log("เพิ่ม list สำเร็จ", response);
                      alert("เพิ่ม list สำเร็จ");
                      resolve();
                      this.setState((prevState) => {
                        let data = [...prevState.data];
                        data = [newData, ...data];
                        return { ...prevState, data };
                      });
                    })
                    .catch((error) => {
                      console.log(error);
                      alert(`เพิ่ม list ไม่สำเร็จ ${error.message}`);
                    });
                }),
              onRowUpdate: (newData, oldData) =>
              
                new Promise((resolve) => {
                  setTimeout(() => {
                   
                    newData = { ...newData, shop: shop.id, userId: shop.userId };

                  axios
                    .put(`http://localhost:9000/api/list/updateListId/${oldData.id}`, newData)
                    .then((response) => {
                      console.log("แก้ไข list สำเร็จ", response);
                      alert("แก้ไขรายการสำเร็จ");
                      resolve();
                      if (oldData) {
                        this.setState((prevState) => {
                          const data = [...prevState.data];
                          data[data.indexOf(oldData)] = newData;
                          return { ...prevState, data };
                        });
                      }
                    }, 600);
                    })
                    .catch((error) => {
                      console.log(error);
                      alert(`เพิ่ม list ไม่สำเร็จ ${error.message}`);
                    });
                    
                }),

              onRowDelete: (oldData) =>
                new Promise((resolve) => {
                  setTimeout(() => {
                    axios.delete(
                      `http://localhost:9000/api/list/delete/${oldData.id}`
                    );
                    console.log("ลบ list สำเร็จ");
                    alert("ลบรายการสำเร็จ");
                    resolve();
                    this.setState((prevState) => {
                      const data = [...prevState.data];
                      data.splice(data.indexOf(oldData), 1);
                      return { ...prevState, data };
                    });
                  }, 600);
                }),
            }}
          />
        </div>
      </div>
    );
  }
}
const mapStateToProps = state => ({
  userInfo: state.user
});

const mapDispatchToProps = dispatch => {};

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

