import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import {
  Dialog,
  Button,
  DialogActions,
  DialogContent,
  Typography,
  DialogContentText,
  DialogTitle,
  Paper,
  InputBase,
  Divider,
  IconButton,
  InputAdornment,
  TextField,
} from "@material-ui/core";
import AppBra from "../../components/AppBra";
import { withRouter } from "react-router-dom";
import compose from "recompose/compose";
import { DatePicker } from "@material-ui/pickers";
import { injectIntl, FormattedRelativeTime } from "react-intl";
import { th } from "date-fns/locale";
import { format } from "date-fns";
import MenuIcon from "@material-ui/icons/Menu";
import axios from "axios";
import SearchIcon from "@material-ui/icons/Search";
import DirectionsIcon from "@material-ui/icons/Directions";
import ListIcon from "@material-ui/icons/List";
import AssignmentIndIcon from "@material-ui/icons/AssignmentInd";
import Rating from "@material-ui/lab/Rating";
import MaterialTable from "material-table";
import moment from "moment";
import "moment/locale/th";
import { handleClickOpenQ, handleCloseQ } from "../ShopPage";
import { connect } from "react-redux";
const styles = (theme) => ({
  root: {
    // padding: "2px 4px",
    display: "flex",
    alignItems: "center",
    width: 400,
    "& .MuiTextField-root": {
      margin: theme.spacing(1),
      marginTop: theme.spacing(2),
      width: "100%",
    },
  },
  margin: {
    margin: theme.spacing(1),
  },

  input: {
    marginLeft: theme.spacing(1),
    flex: 1,
  },
  iconButton: {
    padding: 10,
  },
  divider: {
    height: 28,
    margin: 4,
  },
  modal: {
    display: "flex",
    padding: theme.spacing(1),
    alignItems: "center",
    justifyContent: "center",
  },
});
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: "ช่าง",
  },
];
class HomePage extends Component {
  state = {
    tab: 0,
    date: new Date(),
    open: false,
    list: false,
    rating: 0,
    shops: [],
    columns: [{ title: "เวลา", field: "time" }],
    data: [],
    shopName: null,
    datalist: [],
    beautician: [],
    booking: {
      list: "",
      beautician: "",
    },
  };
  handleClickOpen = () => {
    this.setState({
      open: true,
    });
  };
  handleClose = () => {
    this.setState({
      open: false,
    });
  };
  ClickOpen = () => {
    this.setState({
      list: true,
    });
  };
  Close = () => {
    this.setState({
      list: false,
    });
  };

  componentDidMount = async () => {
    let { pathname } = this.props.location;
    pathname = pathname.substring(1, pathname.length);
    // console.log('pathname', pathname)
    const tab =
      pathname === "สปาและนวด"
        ? 0
        : pathname === "ผิวหน้า"
        ? 1
        : pathname === "ขนตาและคิ้ว"
        ? 2
        : pathname === "ทำเล็บ"
        ? 3
        : pathname === "ซาลอน"
        ? 4
        : pathname === "แต่หน้าทำผม"
        ? 5
        : 0;
        // const result = tab.filter((tab) => {
         
        //   return (
        //     const response = await axios.get("http://localhost:9000/api/shop/all");
              
        //   );
        // })
        
    const response = await axios.get("http://localhost:9000/api/shop/all");
   
    const {response2,responsedata }="";
    for (let i = 0; i < response.data.length; i++) {
      const resposeimgshop = await axios.get(
        `http://localhost:9000/api/storage/file/shop/${response.data[i].id}`
      );
      // console.log(resposeimgshop);

      response.data[i].image =
        "data:" +
        resposeimgshop.data.type +
        ";base64," +
        resposeimgshop.data.url;


        const response2 = await axios.get(
          `http://localhost:9000/api/list/getListshop/${response.data[i].id}`
        );
        const responsedata = await axios.get(
          `http://localhost:9000/api/beautician/getbeauticianShopId/${response.data[i].id}`
        );
        this.setState({
          
          datalist: response2.data,
          beautician: responsedata.data,
        });
    }
    

    // const result="";
    // for (let i = 0; i < response.data.length; i++) {
    //   let { timeopen, timeclose } = response[i].data;
    //   timeopen = timeopen.split(":");
    //   timeclose = timeclose.split(":");
    //   let dateClose = new Date();
    //   dateClose.setHours(parseInt(timeclose[0]));
    //   dateClose.setMinutes(parseInt(timeclose[1]));
    //   result = this.calculate(moment(dateClose), timeopen);
    // }
   
    console.log("response", response.data);
    this.setState({
      tab: tab,
      shops: response.data,
      // data: result,
      // datalist: response2.data,
      // beautician: responsedata.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;
  };

  handleChangeTab = (event, newValue) => {
    const tab =
      newValue === 0
        ? "สปาและนวด"
        : newValue === 1
        ? "ผิวหน้า"
        : newValue === 2
        ? "ขนตาและคิ้ว"
        : newValue === 3
        ? "ทำเล็บ"
        : newValue === 4
        ? "ซาลอน"
        : newValue === 5
        ? "แต่งหน้าทำผม"
        : "สปาและนวด";
    this.setState({ tab: newValue });
    // this.props.history.push(`/${tab}`);
  };

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

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

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

    this.setState({
      shopName,
    });
  };
  render() {
    const { classes ,userInfo} = this.props;
    // const tab = this.state.tab;
    // หรือ
    const {
      tab,
      date,
      open,
      list,
      value,
      rating,
      shops,
      columns,
      data,
      shopName,
      datalist,
      beautician,
      booking,
    } = this.state;
    return (
      <div>
        {/* <AppBra tab={tab} handleChangeTab={this.handleChangeTab} /> */}

        <div className="row mt-5 ">
          <div className="row mt-2 mb-2  ">
            <div className="row ">
              <center>
                <Paper component="form" className={classes.root}>
                  <InputBase
                    className={classes.input}
                    inputProps={{ "aria-label": "ค้นหาร้าน" }}
                    name="shopName"
                    value={shopName}
                    onChange={this.handleChange}
                  />
                  <IconButton
                    type="submit"
                    className={classes.iconButton}
                    aria-label="search"
                    onClick={(e) => {
                      e.preventDefault();
                      axios
                        .post("http://localhost:9000/api/shop/searchShop", {
                          name: shopName,
                        })
                        .then(async (response) => {
                          for (let i = 0; i < response.data.length; i++) {
                            const resposeimgshop = await axios.get(
                              `http://localhost:9000/api/storage/file/shop/${response.data[i].id}`
                            );
                            console.log(resposeimgshop);

                            response.data[i].image =
                              "data:" +
                              resposeimgshop.data.type +
                              ";base64," +
                              resposeimgshop.data.url;
                          }
                          this.setState({ shops: response.data });
                          console.log("ค้นหาสำเร็จ", response);
                          // alert("ค้นหาสำเร็จ");
                        })
                        .catch((error) => {
                          console.log(error);
                          alert("ค้นหาไม่สำเร็จ");
                        });
                    }}
                  >
                    <SearchIcon />
                  </IconButton>
                </Paper>
              </center>
            </div>
          </div>

          {shops.map((shop) => (
            <div className="row mt-5 mb-2 ">
              <div className="col s12 m6 l6">
                <div className="row  mt-3 mb-2 center">
                  <img
                    src={shop.image}
                    width="60%"
                    onClick={() => {
                      this.props.history.push("/ShopPage", { id: shop.id });
                    }}
                  />
                </div>
              </div>

              <div className="col s12 m6 l4">
                <div className="row mt-2 mb-2">
                  <h3>
                    {shop.name}&nbsp; &nbsp;
                    {shop.nameeng}
                  </h3>
                </div>

                <div className="row mt-2 mb-2">{shop.address}</div>

                <div className="row  mt-3 mb-2">{shop.detail}</div>
                <div className="row  mt-3 mb-2">
                  {/* <div className={classes.root}>
                    <Rating
                      name="size-large"
                      defaultValue={3.5}
                      size="large"
                      readOnly
                    />
                  </div> */}
                </div>

                <div className="row center">
                  {/* <Button
                    variant="outlined"
                    color="primary"
                    onClick={this.handleClickOpen}
                  >
                    จองคิว
                  </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.handleClose}
                        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.handleClose();
                        }}
                      >
                        ยืนยัน
                      </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)(HomePage));

