import React, { Component, useState } from "react";
import { withStyles } from "@material-ui/core/styles";
import { withRouter } from "react-router-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { compose } from "recompose";
import AppBar from "../../components/AppBra";
import {
  Button,
  CardHeader,
  Avatar,
  IconButton,
  CardMedia,
  CardActions,
  CardContent,
  Typography,
  Card,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  InputAdornment,
  TextField,
  InputBase,
} from "@material-ui/core";
import GoogleMapReact from "google-map-react";
import Marker from "./marker";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import { DatePicker } from "@material-ui/pickers";
import { injectIntl, FormattedRelativeTime } from "react-intl";
import { th } from "date-fns/locale";
import { format } from "date-fns";
import Rating from "@material-ui/lab/Rating";
import ListIcon from "@material-ui/icons/List";
import AssignmentIndIcon from "@material-ui/icons/AssignmentInd";
import axios from "axios";
import { connect } from "react-redux";
import MaterialTable from "material-table";
import moment from "moment";
import "moment/locale/th";

const styles = (theme) => ({
  root: {
    minWidth: 275,
    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",
    },
  },

  bullet: {
    display: "inline-block",
    margin: "0 2px",
    transform: "scale(0.8)",
  },
  title: {
    fontSize: 14,
  },
  pos: {
    marginBottom: 12,
  },

  modal: {
    display: "flex",
    padding: theme.spacing(1),
    alignItems: "center",
    justifyContent: "center",
  },
  fab: {
    position: "absolute",
    bottom: theme.spacing(2),
    right: theme.spacing(2),
  },
});
const currencieslist = [
  {
    value: "1",
    label: "    กรุณาเลือกรายการ   ",
  },
  {
    value: "2",
    label: "อบไอน้ำ 30 นาที",
  },
  {
    value: "3",
    label: "นวดหน้า 60 นาที ",
  },
  {
    value: "4",
    label: "สระได 20 นาที",
  },
  {
    value: "5",
    label: "ทำเล็บ 60 นาที",
  },
  {
    value: "6",
    label: "ยืดผมถาวร 120 นาที",
  },
  {
    value: "7",
    label: "ทำสีผม 60 นาที",
  },
];
const currencies = [
  {
    value: "1",
    label: "    กรุณาเลือกช่าง    ",
  },
  {
    value: "2",
    label: "ช่าง ก",
  },
  {
    value: "3",
    label: "ช่าง ข",
  },
  {
    value: "4",
    label: "ช่าง ค",
  },
  {
    value: "5",
    label: "ช่าง ง",
  },
  {
    value: "6",
    label: "ช่าง จ",
  },
  {
    value: "7",
    label: "ช่าง",
  },
];
const currenciesreview = [
  {
    value: "1",
    label: "    กรุณาเลือกหัวข้อการรีวิว    ",
  },
  {
    value: "รีวิวช่าง",
    label: "รีวิวช่าง",
  },
  {
    value: "รีวิวร้าน",
    label: "รีวิวร้าน",
  },
  {
    value: "การให้บริการ",
    label: "การให้บริการ",
  },
  {
    value: "การต้อนรับ",
    label: "การต้อนรับ",
  },
  {
    value: "บรรยากาศ",
    label: "บรรยากาศ",
  },
  {
    value: "อื่นๆ",
    label: "อื่นๆ",
  },
];
const currenciespoint = [
  {
    value: "0",
    label: "    กรุณาเลือกคะแนน    ",
  },
  {
    value: "0.5",
    label: "0.5",
  },
  {
    value: "1",
    label: "1",
  },
  {
    value: "1.5",
    label: "1.5",
  },
  {
    value: "2",
    label: "2",
  },
  {
    value: "2.5",
    label: "2.5",
  },
  {
    value: "3",
    label: "3",
  },
  {
    value: "3.5",
    label: "3.5",
  },
  {
    value: "4",
    label: "4",
  },
  {
    value: "4.5",
    label: "4.5",
  },
  {
    value: "5",
    label: "5",
  },
];
class ShopPage extends Component {
  state = {
    reviweOpen: false,
    list: false,
    date: new Date(),
    // open: true,
    open: false,
    shop: null,
    review: {
      topic: null,
      message: null,
      point: null,
    },
    columns: [{ title: "เวลา", field: "time" }],
    columnslist: [
      { title: "ชื่อรายการ", field: "name" },
      { title: "ราคา", field: "price" },

      { title: "เวลาที่จอง", field: "time" },
    ],
    data: [],
    selectedRow: null,
    datalist: [],
  };

  handleClickOpenreview = () => {
    this.setState({
      reviweOpen: true,
    });
  };
  handleClosereview = () => {
    this.setState({
      reviweOpen: false,
    });
  };
  handleClickOpenQ = () => {
    this.setState({
      open: true,
    });
  };
  handleCloseQ = () => {
    this.setState({
      open: false,
    });
  };

  handleSaveQ = () => {
    this.setState({
      open: false,
    });
  };

  ClickOpen = () => {
    this.setState({
      list: true,
    });
  };
  Close = () => {
    this.setState({
      list: false,
    });
  };

  handleChange = (event) => {
    let { review } = this.state;
    console.log("name : ", event.target.name);
    console.log("value : ", event.target.value);

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

    this.setState({
      review,
    });
  };

  handleChangeDate = (newDate) => {
    console.log("newDate: ", newDate);
    this.setState({
      date: newDate,
    });
  }; 

  componentDidMount = async () => {
    const { location, userInfo } = this.props;
    const id = location.state.id;
    const response1 = await axios.get(
      `http://localhost:9000/api/shop/getShopId/${id}`
    );
    const response2 = await axios.get(
     `http://localhost:9000/api/list/getListshop/${id}`
    );
    console.log("response", response1.data);
    console.log("response", response2.data);
    let { timeopen, timeclose } = response1.data;
    timeopen = timeopen.split(":");
    timeclose = timeclose.split(":");
    let dateClose = new Date();
    dateClose.setHours(parseInt(timeclose[0]));
    dateClose.setMinutes(parseInt(timeclose[1]));
    const result = this.calculate(moment(dateClose), timeopen);

   
    this.setState({
      shop: response1.data,
      data: result,
      datalist: response2.data
    });

  };

  calculate = (endTime, timeopen) => {
    let timeStops = [];
    let dateOpen = new Date();
    dateOpen.setHours(parseInt(timeopen[0]));
    dateOpen.setMinutes(parseInt(timeopen[1]));
    let startTime = moment(dateOpen).add(
      "m",
      15 - (moment(dateOpen).minute() % 15)
    );

    while (startTime < endTime) {
      timeStops.push({
        time: new moment(startTime).format("LT"),
      });
      startTime.add("m", 15);
    }

    return timeStops;
  };

  render() {
    const { classes, userInfo } = this.props;
    const bull = <span className={classes.bullet}>•</span>;
    const {
      shop,
      review,
      reviweOpen,
      list,
      date,
      open,
      columns,
      data,
      datalist,
      selectedRow,
      columnslist,
    } = this.state;

    return (
      <div>
        <AppBar />

        {shop && (
          <div className="row">
            <div className="row mt-2 mb-2">
              <div className="col s12 m6 l1"></div>
              <div className="col s12 m6 l11">
                <h3>
                  {shop.name}&nbsp; &nbsp;{shop.nameeng}
                </h3>
                {shop.address}
              </div>
            </div>
            <div c>
              <div className="col s12 m6 l8">
                <div className="row center">
                  <img
                    src="https://www.smeleader.com/wp-content/uploads/2018/05/%E0%B9%81%E0%B8%9F%E0%B8%A3%E0%B8%99%E0%B9%84%E0%B8%8A%E0%B8%AA%E0%B9%8C%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%99%E0%B9%80%E0%B8%AA%E0%B8%A3%E0%B8%B4%E0%B8%A1%E0%B8%AA%E0%B8%A7%E0%B8%A2-%E0%B8%A3%E0%B8%A7%E0%B8%A1%E0%B9%81%E0%B8%9A%E0%B8%A3%E0%B8%99%E0%B8%94%E0%B9%8C%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%99%E0%B8%8B%E0%B8%B2%E0%B8%A5%E0%B8%AD%E0%B8%99-%E0%B8%AA%E0%B8%B2%E0%B8%99%E0%B8%9D%E0%B8%B1%E0%B8%99%E0%B8%98%E0%B8%B8%E0%B8%A3%E0%B8%81%E0%B8%B4%E0%B8%88%E0%B8%97%E0%B8%A3%E0%B8%87%E0%B8%9C%E0%B8%A1.jpg"
                    width="90%"
                  ></img>
                </div>
                <div className="row center">
                  <Button
                    variant="contained"
                    color="secondary"
                    onClick={this.ClickOpen}
                  >
                    รายการ
                  </Button>{" "}
                  <Dialog
                    open={list}
                    fullWidth={true}
                    // maxWidth="mr"
                    onClose={this.Close}
                    aria-labelledby="max-width-dialog-title"
                  >
                    <DialogTitle id="max-width-dialog-title">
                      รายการ
                    </DialogTitle>
                    <DialogContent>
                      <DialogContentText>
                        <div className="row">
                          <MaterialTable
                            title="รายการ"
                            columns={columnslist}
                            data={datalist}
                            options={{
                              selection: false,
                            }}
                          />
                        </div>
                      </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                      <Button onClick={this.Close} color="primary">
                        Close
                      </Button>
                    </DialogActions>
                  </Dialog>
                  &nbsp; &nbsp; &nbsp;
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={this.handleClickOpenQ}
                  >
                    จองคิว
                  </Button>
                  <Dialog
                    open={open}
                    fullWidth={true}
                    maxWidth="md"
                    onClose={this.handleCloseQ}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                  >
                    <DialogTitle id="alert-dialog-title">
                      {"จองคิว"}
                    </DialogTitle>
                    <DialogContent>
                      <div className="row">
                        <div className="col s12 m5">
                          <div
                            style={{
                              maxWidth: "fit-content",
                            }}
                          >
                            <DatePicker
                              autoOk
                              orientation="static"
                              variant="static"
                              openTo="date"
                              minDate={new Date()}
                              value={date}
                              onChange={this.handleChangeDate}
                            />
                          </div>
                        </div>
                        <div className="col s12 m7">
                          <Typography>
                            วันที่ที่เลือกคือ{" "}
                            {format(new Date(date), "dd MMMM yyyy", {
                              locale: th,
                            })}
                          </Typography>
                          <div className="mt-2">
                            <Typography>กรุณาเลือกข้อมูลการจอง</Typography>
                            <div className="row mt-2">
                              <div className="col">
                                <TextField
                                  className={classes.margin}
                                  id="list"
                                  name="list"
                                  select
                                  label="เลือกรายการ*"
                                  onChange={this.handleChange}
                                  SelectProps={{
                                    native: true,
                                  }}
                                  variant="outlined"
                                  InputProps={{
                                    startAdornment: (
                                      <InputAdornment position="start">
                                        <ListIcon />
                                      </InputAdornment>
                                    ),
                                  }}
                                >
                                  {datalist.map((datalist) => (
                                    <option
                                      key={datalist.id}
                                      value={datalist.id}
                                    >
                                      {datalist.name}
                                    </option>
                                  ))}
                                </TextField>
                              </div>
                              <div className="col">
                                <TextField
                                  className={classes.margin}
                                  id="list"
                                  name="list"
                                  select
                                  label="เลือกช่าง*"
                                  onChange={this.handleChange}
                                  SelectProps={{
                                    native: true,
                                  }}
                                  variant="outlined"
                                  InputProps={{
                                    startAdornment: (
                                      <InputAdornment position="start">
                                        <AssignmentIndIcon />
                                      </InputAdornment>
                                    ),
                                  }}
                                >
                                  {currencies.map((option) => (
                                    <option
                                      key={option.value}
                                      value={option.value}
                                    >
                                      {option.label}
                                    </option>
                                  ))}
                                </TextField>
                              </div>
                              <div className="col s12 mt-2">
                                <MaterialTable
                                  title=""
                                  columns={columns}
                                  data={data}
                                  onRowClick={(evt, selectedRow) => {
                                    console.log("selectedRow", selectedRow);
                                    this.setState({ selectedRow });
                                  }}
                                  options={{
                                    selection: false,
                                    search: false,
                                    showTitle: false,
                                    toolbar: false,
                                    rowStyle: (rowData) => ({
                                      backgroundColor:
                                        this.state.selectedRow &&
                                        this.state.selectedRow.tableData.id ===
                                          rowData.tableData.id
                                          ? "#EEE"
                                          : "#FFF",
                                    }),
                                  }}
                                />
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </DialogContent>
                    <DialogActions>
                      <Button
                        variant="outlined"
                        onClick={this.handleCloseQ}
                        color="secondary"
                      >
                        ยกเลิก
                      </Button>
                      <Button
                        variant="outlined"
                        color="primary"
                        onClick={this.handleSaveQ}
                      >
                        ยืนยัน
                      </Button>
                    </DialogActions>
                  </Dialog>
                </div>
              </div>

              <div className="col s12 m6 l4">
                <div className="row">
                  <center>
                    <div style={{ height: "50vh", width: "100%" }}>
                      <GoogleMapReact
                        bootstrapURLKeys={{
                          key: "AIzaSyBJWuQmrf6UgrkGbMJF6-m1GwTZrazBFBo",
                        }}
                        defaultCenter={{
                          lat: shop.lat * 1,
                          lng: shop.lng * 1,
                        }}
                        defaultZoom={16}
                      >
                        <Marker
                          lat={shop.lat * 1}
                          lng={shop.lng * 1}
                          text={`My Marker2`}
                        />
                      </GoogleMapReact>
                    </div>
                  </center>
                </div>
                <div className="row">
                  <h4>ที่อยู่ :&nbsp;{shop.address}</h4>
                </div>

                <div className="row">
                  <h4>เบอร์โทร : {shop.tel}</h4>
                  <h4>เวลาเปิด : {shop.timeopen} น.</h4>
                  <h4>เวลาปิด : {shop.timeclose} น.</h4>
                </div>
              </div>
            </div>

            <div className="row mt-2 mb-2">
              <div className="col s12 m5 l7">
                <div className="row center">
                  <h4>ผลงานช่าง ปิยพร อาภรศรี</h4>
                  <div className="col s12 m12 l6 mb-5">
                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSAaEt_unwBuDLyqCP_bW3PBawVHkjZrNq-F3u7mAKtSjmBTrHE"></img>
                  </div>
                  <div className="col s12 m12 l6 mb-5">
                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSAaEt_unwBuDLyqCP_bW3PBawVHkjZrNq-F3u7mAKtSjmBTrHE"></img>
                  </div>
                </div>
              </div>
              <div className="col s12 m1 l1"></div>
              <div className="col s12 m6 l4">
               
                <div className="row">
                  <Card className={classes.root} variant="outlined">
                    <CardHeader
                      avatar={
                        <Avatar aria-label="recipe" className={classes.avatar}>
                          R
                        </Avatar>
                      }
                      action={
                        <IconButton aria-label="settings">
                          <MoreVertIcon />
                        </IconButton>
                      }
                      title="Shrimp and Chorizo Paella"
                      subheader="September 14, 2016"
                    />
                    <div className="row center">
                      <div className={classes.root}>
                        <Rating
                          name="size-large"
                          defaultValue={3.5}
                          size="small"
                          readOnly
                        />
                      </div>
                    </div>

                    <CardMedia
                      className={classes.media}
                      image="/static/images/cards/paella.jpg"
                      title="Paella dish"
                    />
                    <CardContent>
                      <Typography
                        variant="body2"
                        color="textSecondary"
                        component="p"
                      >
                        This impressive paella is a perfect party dish and a fun
                        meal to cook together with your guests. Add 1 cup of
                        frozen peas along with the mussels, if you like.
                      </Typography>
                    </CardContent>
                  </Card>
                </div>
                <div className="row right">
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={this.handleClickOpenreview}
                  >
                    เขียนรีวิว
                  </Button>
                  <Dialog
                    open={reviweOpen}
                    // TransitionComponent={Transition}
                    keepMounted
                    onClose={this.handleClosereview}
                    aria-labelledby="alert-dialog-slide-title"
                    aria-describedby="alert-dialog-slide-description"
                  >
                    <DialogTitle id="alert-dialog-slide-title">
                      เขียนรีวิวติชม
                    </DialogTitle>
                    <DialogContent>
                      <DialogContentText id="alert-dialog-slide-description">
                        <div className="row mt-4 mb-2">
                          <TextField
                            className={classes.margin}
                            id="topic"
                            name="topic"
                            value={review.topic}
                            select
                            label="หัวข้อรีวิว"
                            onChange={this.handleChange}
                            SelectProps={{
                              native: true,
                            }}
                            variant="outlined"
                            InputProps={{
                              startAdornment: (
                                <InputAdornment position="start">
                                  <ListIcon />
                                </InputAdornment>
                              ),
                            }}
                          >
                            {currenciesreview.map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </TextField>
                        </div>
                        <div className="row mt-4 mb-2">
                          <TextField
                            className={classes.margin}
                            id="message"
                            name="message"
                            value={review.message}
                            label="ข้อความรีวิว"
                            variant="outlined"
                            InputProps={{
                              startAdornment: (
                                <InputAdornment position="start">
                                  {/* <AccountCircle /> */}
                                </InputAdornment>
                              ),
                            }}
                            onChange={this.handleChange}
                          />
                        </div>
                        <div className="row mt-4 mb-2">
                          <TextField
                            className={classes.margin}
                            id="point"
                            name="point"
                            value={review.point}
                            select
                            label="คะแนน"
                            onChange={this.handleChange}
                            SelectProps={{
                              native: true,
                            }}
                            variant="outlined"
                            InputProps={{
                              startAdornment: (
                                <InputAdornment position="start">
                                  <ListIcon />
                                </InputAdornment>
                              ),
                            }}
                          >
                            {currenciespoint.map((option) => (
                              <option key={option.value} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </TextField>
                        </div>
                      </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                      <Button
                        onClick={this.handleCloserevie}
                        color="primary"
                      >
                        ยกเลิก
                      </Button>
                      <Button
                        onClick={() => {
                          if(userInfo.id){
                            axios
                            .post("http://localhost:9000/api/review/add", {
                              ...review,
                              shop: shop.id,
                              userID: userInfo.id,
                            })
                            .then((response) => {
                              console.log("เขียนรีวิวสำเร็จ", response);
                              alert("เขียนรีวิวสำเร็จ");
                            })
                            .catch((error) => {
                              console.log(error);
                              alert("คุณยังไม่ได้ทำการ login ");
                              this.props.history.push("/LoginPage");
                            });
                          }
                          else{
                            alert("คุณยังไม่ได้ทำการ login ");
                              this.props.history.push("/LoginPage");
                          }
                         
                        }}
                        color="primary"
                      >
                        ยันยัน
                      </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)(ShopPage));
