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 { red } from "@material-ui/core/colors";
import MaterialTable from "material-table";
import moment from "moment";
import FacebookIcon from "@material-ui/icons/Facebook";
import "moment/locale/th";

const styles = (theme) => ({
  root: {
    minWidth: 275,
    height: 200,
    flexGrow: 1,
    maxheight: 345,
    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: [],
    columns: [{ title: "เวลา", field: "time" }],
    columnslist: [
      { title: "ชื่อรายการ", field: "name" },
      { title: "ราคา", field: "price" },

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

  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, booking } = this.state;
    console.log("name : ", event.target.name);
    console.log("value : ", event.target.value);

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

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

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

  componentDidMount = async () => {
    const { location, userInfo } = this.props;
    const id = location.state.id;
    const { beauticianimg } = this.state;
    const response1 = await axios.get(
      `http://localhost:9000/api/shop/getShopId/${id}`
    );
    const response2 = await axios.get(
      `http://localhost:9000/api/list/getListshop/${id}`
    );
    const responsereview = await axios.get(
      `http://localhost:9000/api/review/getReviewShopid/${response1.data.id}`
    );
    const resposeimgshop = await axios.get(
      `http://localhost:9000/api/storage/file/shop/${response1.data.id}`
    );
    //     const resposeimgwork = await axios.get(
    //       `http://localhost:9000/api/storageshop/file/shop/${response1.data.id}`
    //     );
    //     for (let i = 0; i < resposeimgwork.length; i++) {

    //       resposeimgwork[i].image = ('data:' + resposeimgshop.data.type+';base64,'+resposeimgshop.data.url)
    // }
    // console.log(resposeimgshop);
    const responsedata = await axios.get(
      `http://localhost:9000/api/beautician/getbeauticianShopId/${response1.data.id}`
    );

    response1.data.image =
      "data:" + resposeimgshop.data.type + ";base64," + resposeimgshop.data.url;

    console.log("response", response1.data);
    console.log("response", response2.data);
    console.log("response", responsereview.data);
    console.log("response", responsedata.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);
    // tmp = [a,b,c]
    // if(x === b){
    //  remove b from tmp
    // }
    // render tmp
    this.setState({
      shop: response1.data,
      data: result,
      datalist: response2.data,
      beautician: responsedata.data,
      review: responsereview.data,
      // shopimg:resposeimgwork.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,
      beautician,
      booking,
      shopimg,
      beauticianimg,
    } = 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>
              <div className="col s12 m6 l8">
                <div className="row center">
                  <img src={shop.image} 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"
                                  value={booking.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.name}
                                    >
                                      {datalist.name}
                                    </option>
                                  ))}
                                </TextField>
                              </div>
                              <div className="col">
                                <TextField
                                  className={classes.margin}
                                  id="beautician"
                                  name="beautician"
                                  value={booking.beautician}
                                  select
                                  label="เลือกช่าง*"
                                  onChange={this.handleChange}
                                  SelectProps={{
                                    native: true,
                                  }}
                                  variant="outlined"
                                  InputProps={{
                                    startAdornment: (
                                      <InputAdornment position="start">
                                        <AssignmentIndIcon />
                                      </InputAdornment>
                                    ),
                                  }}
                                >
                                  {beautician.map((beautician) => (
                                    <option
                                      key={beautician.id}
                                      value={beautician.name}
                                    >
                                      {beautician.name}
                                    </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={() => {
                          axios
                            .post("http://localhost:9000/api/booking/add", {
                              // ...booking,
                              name: userInfo.name,
                              shop: shop.id,
                              list: booking.list,
                              beautician: booking.beautician,
                              date: new Date(date),
                              time: selectedRow.time,
                              name: userInfo.name,
                            })
                            .then((response) => {
                              console.log("ทำการจองคิวสำเร็จ", response);
                              alert("ทำการจองคิวสำเร็จ");
                            })
                            .catch((error) => {
                              console.log(error);
                              alert("คุณยังไม่ได้ทำการ login ");
                              this.props.history.push("/LoginPage");
                            });
                          this.handleCloseQ();
                        }}
                      >
                        ยืนยัน
                      </Button>
                    </DialogActions>
                  </Dialog>
                  &nbsp; &nbsp; &nbsp;
                  <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. handleClosereview } color="primary">
                        ยกเลิก
                      </Button>
                      <Button
                        onClick={() => {
                          axios
                            .post("http://localhost:9000/api/review/add", {
                              ...review,
                              shop: shop.id,
                              name: userInfo.name,
                            })
                            .then((response) => {
                              console.log("เขียนรีวิวสำเร็จ", response);
                              alert("เขียนรีวิวสำเร็จ");
                              this. handleClosereview ();
                            })
                            
                            .catch((error) => {
                              console.log(error);
                              // this.handleCloserevie();
                              // alert("คุณยังไม่ได้ทำการ login ");
                              // this.props.history.push("/LoginPage");
                            });
                            // this.handleCloserevie();
                        }}
                        color="primary"
                      >
                        ยันยัน
                      </Button>
                    </DialogActions>
                  </Dialog>
                
                  {/* <div className="row center mt-5">
                    <h4>ผลงานร้าน {shop.name}</h4>
                    {shopimg.image.map(shopimg=> (
                    <div className="col s12 m12 l6 mb-5">
                      <img src={shopimg.image}></img>
                    </div> 
                    ))}
                  </div> */}
                  {/* {beautician.map((beautician) => (
                    <div className="row center mt-5">
                      <h4>ผลงานช่าง {beautician.name}</h4>
                      <div className="col s12 m12 l6 mb-5">
                        <img src={beautician.image}></img>
                      </div>
                    </div>
                  ))} */}
                </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>
                  <Button
                    variant="contained"
                    color="primary"
                    disableElevation
                    href={shop.facebook}
                  >
                    <FacebookIcon />
                  </Button>
                </div>
                
                
              </div>

              <div className="col s12 m8 l8">
                
                  
                {review.map((review) => (
                  <div className="row">
                    <Card className={classes.root} variant="outlined">
                      <CardHeader
                        avatar={
                          <Avatar
                            aria-label="recipe"
                            className={classes.avatar}
                          >
                            {review.name.slice(0, 1)}
                          </Avatar>
                        }
                        title={review.name}
                        subheader={review.updatedAt}
                      />

                      <CardContent>
                        <Typography>
                          <div className="row center">
                            <Rating
                              name="size-large"
                              defaultValue={review.point}
                              size="small"
                              readOnly
                            />
                          </div>
                          <b>{review.topic}</b> : {review.message}
                        </Typography>
                      </CardContent>
                    </Card>
                  </div>
                ))}
               
              </div>
              <div className="col s12 m4 l4">
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}

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

const mapDispatchToProps = (dispatch) => {};

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