import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { withStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import List from "@material-ui/core/List";
import CircularProgress from "@material-ui/core/CircularProgress";
// import MenuItem from "@material-ui/core/MenuItem";
// import Typography from "@material-ui/core/Typography";
// import TextField from "@material-ui/core/TextField";
import Divider from "@material-ui/core/Divider";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import axios from "axios";
import FlatButton from "material-ui/FlatButton";
import Dialog from "material-ui/Dialog";
import { isMobile } from "react-device-detect";
import cookie from "react-cookies";
import api from "./api/api";
const drawerWidth = 240;
let click_width = "";
const styles = theme => ({
  root: {
    flexGrow: 1
  },

  appBar: {
    boxShadow: "none",
    color: "#000",
    backgroundColor: "transparent",
    position: "absolute",
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    })
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen
    })
  },
  "appBarShift-left": {
    marginLeft: drawerWidth,
    display: "none"
  },
  "appBarShift-right": {
    marginRight: drawerWidth
  },
  menuButton: {
    marginLeft: 0,
    marginRight: 20
  },
  hide: {
    display: "none"
  },
  drawerPaper: {
    position: "relative",
    width: drawerWidth,
    float: "left"
  },

  drawerHeader: {
    display: "flex",
    alignItems: "center",
    justifyContent: "flex-end",
    padding: "0 8px",
    ...theme.mixins.toolbar
  },
  content: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.default,
    padding: 0,
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    })
  },
  "content-left": {
    marginLeft: -drawerWidth
  },
  "content-right": {
    marginRight: -drawerWidth
  },
  contentShift: {
    transition: theme.transitions.create("margin", {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen
    })
  },
  "contentShift-left": {
    marginLeft: 0
  },
  "contentShift-right": {
    marginRight: 0
  }
});

class PersistentDrawer extends React.Component {
  constructor(props) {
    if (
      cookie.load("user_id") == "" ||
      cookie.load("user_id") == "undefined" ||
      typeof cookie.load("user_id") == undefined
    ) {
      props.history.push("/");
    }
    super(props);
    console.log("this.prop", this.props);
    this.state = {
      open: false,
      anchor: "left",
      dialogopen: false,
      alertmsg: "",
      is_login: false,
      login: "",
      loader: false,
      nocontest: false,
      push_contest: false
    };
    this.handleContest = this.handleContest.bind(this);
    this.handleFreebie = this.handleFreebie.bind(this);
  }
  handleDrawerOpen = () => {
    this.setState({ open: true });
    click_width = "20";
  };

  handleDrawerClose = () => {
    this.setState({ open: false });
    click_width = "";
  };

  handleChangeAnchor = event => {
    this.setState({
      anchor: event.target.value
    });
  };

  handleContest = () => {
    console.log("here");
    localStorage.setItem("current_state", "contest_drawer"),
      this.props.prop.history.push("/contest_drawer");
  };

  handleFreebie = () => {
    console.log("here");
    localStorage.setItem("current_state", "freebie_drawer"),
      this.props.prop.history.push("/freebie_drawer");
  };
  handleClose = () => {
    this.setState({ dialogopen: false });
  };

  render() {
    const { classes, theme } = this.props;
    const { anchor, open } = this.state;

    const drawer = (
      <Drawer
        variant="persistent"
        anchor={anchor}
        open={open}
        classes={{
          paper: classes.drawerPaper
        }}
      >
        <div className={classes.drawerHeader}>
          <IconButton onClick={this.handleDrawerClose}>
            {theme.direction === "rtl" ? (
              <ChevronRightIcon />
            ) : (
              <ChevronLeftIcon />
            )}
          </IconButton>
        </div>
        <Divider />
        <List
          className="drawer_list"
          onClick={() => {
            localStorage.setItem("current_state", "edit"),
              this.props.prop.history.push("/edit");
          }}
        >
          Profile
        </List>
        <Divider />
        <List
          className="drawer_list"
          onClick={() => {
            localStorage.setItem("is_edit", "true"),
              localStorage.setItem("current_state", "family_share"),
              this.props.prop.history.push("/family_share");
          }}
        >
          My Family
        </List>
        <Divider />
        <List
          className="drawer_list"
          onClick={() => {
            !this.state.loader_freebie ? this.handleFreebie() : "";
          }}
        >
          Freebies
          {this.state.loader_freebie && (
            <CircularProgress
              size={20}
              style={{ color: "black", marginLeft: "17%" }}
            />
          )}
        </List>
        <Divider />
        <List
          className="drawer_list"
          onClick={() => {
            !this.state.loader ? this.handleContest() : "";
          }}
        >
          Contests
          {this.state.loader && (
            <CircularProgress
              size={20}
              style={{ color: "black", marginLeft: "17%" }}
            />
          )}
        </List>
        <Divider />
        <List
          className="drawer_list"
          onClick={() => {
            localStorage.clear(),
              cookie.remove("user_id", { path: "/" }),
              cookie.remove("access_token", { path: "/" }),
              cookie.remove("relative_user_id", { path: "/" }),
              cookie.remove("check_user_id", { path: "/" }),
              cookie.remove("relative_refered_by_user_id", { path: "/" }),
              this.props.prop.history.push("/");
          }}
        >
          Logout
        </List>
      </Drawer>
    );

    let before = null;
    let after = null;

    if (anchor === "left") {
      before = drawer;
    } else {
      after = drawer;
    }

    return (
      <div className={classes.root}>
        <Dialog
          style={{ textTransform: "capitalize" }}
          actions={
            <FlatButton
              label="Close"
              onClick={() =>
                this.state.nocontest
                  ? this.props.history.push("/set_relation")
                  : this.handleClose()
              }
            />
          }
          modal={false}
          open={this.state.dialogopen}
          /* onRequestClose={()=>this.state.nocontest?this.props.history.push("/set_relation/"):this.handleClose.bind(this)} */
        >
          {this.state.alertmsg}
        </Dialog>
        <div
          className="drawer"
          style={{
            width: click_width.length > 0 ? (isMobile ? "65%" : "32%") : "8%",
            height: click_width.length > 0 ? "100%" : "11%"
          }}
        >
          {/* <div className="drawer" style={{width: "auto !important"}}> */}
          <AppBar
            className={classNames(classes.appBar, {
              [classes.appBarShift]: open,
              [classes[`appBarShift-${anchor}`]]: open
            })}
          >
            <Toolbar disableGutters={!open}>
              <IconButton
                color="inherit"
                aria-label="open drawer"
                onClick={this.handleDrawerOpen}
                className={classNames(classes.menuButton, open && classes.hide)}
              >
                <MenuIcon />
              </IconButton>
            </Toolbar>
          </AppBar>
          {before}
          <main
            className={classNames(
              classes.content,
              classes[`content-${anchor}`],
              {
                [classes.contentShift]: open,
                [classes[`contentShift-${anchor}`]]: open
              }
            )}
          >
            {/* <div className={classes.drawerHeader} /> */}
          </main>
          {after}
        </div>
      </div>
    );
  }
}

PersistentDrawer.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired
};

export default withStyles(styles, { withTheme: true })(PersistentDrawer);
