import React from "react";
import api from "./api/api";
import axios from "axios";
import CircularProgress from "@material-ui/core/CircularProgress";
import Countdown from "react-countdown-now";
import Drawer from "./drawer";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import { isMobile } from "react-device-detect";
import DatePicker from "react-mobile-datepicker";
import DatePickerMaterial from "material-ui/DatePicker";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import cookie from "react-cookies";
const monthMap = {
  "01": "Jan",
  "02": "Feb",
  "03": "Mar",
  "04": "Apr",
  "05": "May",
  "06": "Jun",
  "07": "Jul",
  "08": "Aug",
  "09": "Sep",
  "10": "Oct",
  "11": "Nov",
  "12": "Dec"
};
let date = [];
let months = [];
let months_name = {
  "1": "Janaury",
  "2": "February",
  "3": "March",
  "4": "April",
  "5": "May",
  "6": "June",
  "7": "July",
  "8": "August",
  "9": "September",
  "10": "October",
  "11": "November",
  "12": "December"
};
let years = [];
class UserBirthDate extends React.Component {
  constructor(props) {
    super(props);
    console.log("session", localStorage.getItem("current_state"));
    console.log("is_active", localStorage.getItem("login_is_active"));
    if (
      localStorage.getItem("current_state") !== "user_birthdate" )  {
        this.props.history.push("/menu_page");
      }
    let contest_id = localStorage.getItem("contest_id");
    console.log("contest_id", contest_id);
    let user_id = cookie.load("user_id");
    console.log("user_id", new Date());
    this.state = {
      isOpen: false,
      loader: false,
      user_id: user_id,
      user_birthdate: "",
      time: new Date("Aug 17 1988"),
      contest_id: contest_id,
      open: false,
      alertmsg: "",
      date: "",
      month: "",
      year: "",
      contest: {},
      familymemberdata: [],
      show_error: false,
      error: "",
      is_active: localStorage.getItem("login_is_active") == 1 ? true : false
    };
    this.changeDate = this.changeDate.bind(this);
    this.handleSelect = this.handleSelect.bind(this);
    this.link_contest = this.link_contest.bind(this);
    this.handleDone = this.handleDone.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
    this.handleChangeDate = this.handleChangeDate.bind(this);
    this.handleChangeMonth = this.handleChangeMonth.bind(this);
    this.handleChangeYear = this.handleChangeYear.bind(this);
  }
  componentDidMount() {
    let contest_detail = localStorage.getItem("contest_detail");
    console.log("contest_detail", JSON.parse(contest_detail));
    this.setState({ contest: JSON.parse(contest_detail) });
    //for date
    for (let i = 1; i < 32; i++) {
      date.push(<MenuItem value={i} key={i+"date"} primaryText={i} />);
    }
    //for month
    for (let i = 1; i < 13; i++) {
      months.push(<MenuItem value={i} key={i+"month"} primaryText={months_name[i]} />);
    }
    //for year
    let min_date = new Date();
    min_date.setFullYear(min_date.getFullYear() - 118);
    let max_date = new Date();
    max_date.setFullYear(max_date.getFullYear() - 18);
    let min_year = min_date.getFullYear();
    let max_year = max_date.getFullYear();
    for (let i = max_year + 1; i > min_year + 1; i--) {
      years.push(
        <MenuItem
          value={i}
          key={i+"year"}
          primaryText={i}
          style={{
            top: "auto",
            bottom: "100%"
          }}
        />
      );
    }
  }

  handleCancel = () => {
    this.setState({ isOpen: false });
  };

  changeDate = (event, value) => {
    console.log("value", value);
    var months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ];
    var month = months[value.getMonth()];
    console.log("month", month);

    let selectedDate =
      month + " " + value.getDate() + " " + value.getFullYear();

    console.log("selectedDate", selectedDate);
    this.setState({ user_birthdate: selectedDate });
  };

  handleSelect = value => {
    var months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ];
    this.setState({ isOpen: false });
    var month = months[value.getMonth()];
    let selectedDate =
      month + " " + value.getDate() + " " + value.getFullYear();

    console.log("selectedDate", selectedDate);
    this.setState({ user_birthdate: selectedDate, time: value,month:month,date:value.getDate(),year:value.getFullYear() });
  };

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

  link_contest = () => {
    console.log("months",this.state);
    var self = this;
    if (
      !this.state.user_birthdate ||
      this.state.user_birthdate == ""
    ) {
      console.log("months", months_name[this.state.month]);
      this.setState({ show_error: true, error: "Enter Valid Date" });
    } else {
      var self = this;
      console.log("months", months_name[this.state.month]);
      let today_date = new Date();
      let today_year = today_date.getFullYear();
      let today_month = today_date.getMonth();
      let today_day = today_date.getDate();
      let age = today_year - this.state.year;

      if (today_month < this.state.month - 1) {
        age = age - 1;
      }
      if (this.state.month - 1 == today_month && today_day < this.state.date) {
        age = age - 1;
      }
      console.log("age",age);
      localStorage.setItem("age",age)
    console.log("this.stae", this.state.user_birthdate);
    var update = {
      action: "update",
      update_contest_entry:{
        contest_id:localStorage.getItem("contest_id"),
      status:age>24?"active":"inactive",
      user_id: cookie.load("user_id"),
      },
      user_id: cookie.load("user_id"),
      user_metadata: {
        birth_date: this.state.user_birthdate
      }
    };
    console.log("update", update);
    this.setState({ loader: true });
    axios
      .request({
        method: "POST",
        url: api.react_request,
        data: JSON.stringify(update)
      })
      .then(response => {
        console.log("response", response);
        if (response.data) {
          self.setState({ loader: false });
          localStorage.setItem(
            "user_birthdate",
            response.data.user_metadata.birth_date
          );
          localStorage.setItem("user_age_required", "true");

          localStorage.setItem("current_state", "share");

          self.props.history.push("/share");
        }
      })
      .catch(error => {
        console.log("error", error);
        self.setState({
          open: true,
          alertmsg: "Something Wrong Try Again Later"
        });
      });
  }
  };

  handleDone = () => {
    console.log("months", months_name[this.state.month]);
    if (
      !this.state.date ||
      !this.state.month ||
      !this.state.year ||
      this.state.date == "" ||
      this.state.month == "" ||
      this.state.year == ""
    ) {
      console.log("months", months_name[this.state.month]);
      this.setState({ show_error: true, error: "Enter Valid Date" });
    } else {
      var self = this;
      console.log("months", months_name[this.state.month]);
      let today_date = new Date();
      let today_year = today_date.getFullYear();
      let today_month = today_date.getMonth();
      let today_day = today_date.getDate();
      let age = today_year - this.state.year;

      if (today_month < this.state.month - 1) {
        age = age - 1;
      }
      if (this.state.month - 1 == today_month && today_day < this.state.date) {
        age = age - 1;
      }
      localStorage.setItem("age",age)
      console.log("age",age);
      var update = {
        action: "update",
        update_contest_entry:{
          contest_id:localStorage.getItem("contest_id"),
        status:age>24?"active":"inactive",
        user_id: cookie.load("user_id"),
        },
        user_id: cookie.load("user_id"),
        user_metadata: {
          birth_date:
            months_name[this.state.month] +
            " " +
            this.state.date +
            " " +
            this.state.year
        }
      };
      console.log("update", update);
      this.setState({ loader: true });
      axios
        .request({
          method: "POST",
          url: api.react_request,
          data: JSON.stringify(update)
        })
        .then(response => {
          console.log("response", response);
          if (response.data) {
            self.setState({ loader: false });
            localStorage.setItem(
              "user_birthdate",
              response.data.user_metadata.birth_date
            );
            localStorage.setItem("user_age_required", "true");

            localStorage.setItem("current_state", "share");

            self.props.history.push("/share");
          }
        })
        .catch(error => {
          console.log("error", error);
          self.setState({
            open: true,
            alertmsg: "Something Wrong Try Again Later"
          });
        });
    }
  };

  handleChangeDate = (event, index, value) => {
    console.log("value", value);
    this.setState({ date: value, show_error: false });
  };
  handleChangeMonth = (event, index, value) => {
    console.log("value", value);
    this.setState({ month: value, show_error: false });
  };
  handleChangeYear = (event, index, value) => {
    console.log("value", value);
    this.setState({ year: value, show_error: false });
  };

  render() {
    // const { open } = this.state;
    return (
      <div className="user_bithdate_first_div">
        <center className="userbirthdatecenter_tag">
          {this.state.is_active && <Drawer prop={this.props} />}
          {this.state.loader && (
            <center>
              <CircularProgress
                size={100}
                style={{ color: "black", marginTop: "17%" }}
              />
            </center>
          )}
          <Dialog
            style={{ textTransform: "capitalize" }}
            actions={
              <FlatButton
                label="OK"
                labelStyle={{ color: "#000" }}
                onClick={() => this.handleClose()}
              />
            }
            modal={false}
            open={this.state.open}
            //onRequestClose={this.handleClose}
          >
            {this.state.alertmsg}
          </Dialog>
          {!this.state.loader &&
            this.state.contest._id && (
              <div className="rowContainerContest user_birthdate_header">
                {/* <Countdown date={Date.now() + 84682835} /> */}
                <div className="rowContainerContest socialshare">
                 <div className="info_icon_div infoicon_birthdatediv user_birthdate_infoicondiv">
                    <img
                      src={api.image_path+"info1.png"}
                      alt="info_img"
                      className="info_img"
                      onClick={() => {
                        localStorage.setItem("info", "user_birthdate"),
                        localStorage.setItem("current_state", "info"),
                          this.props.history.push("/info");
                      }}
                    />
                  </div>
                  <div className="row" style={{ height: 30, paddingTop: 5 }}>
                    <p style={{ fontSize: 20 }}>
                      Ends in:&nbsp;<b>
                        <Countdown
                          date={new Date(this.state.contest.expiry_date.replace(/-/g, "/"))}
                        />
                      </b>
                    </p>
                  </div>
                  <div className="row contest_row">
                    <div className="col-md-6 contest_row1">
                      <img
                        src={api.image_path+ this.state.contest.logo}
                        className="contest_logo_img"
                      />
                    </div>
                    <div
                      className="col-md-6 contest_row2"
                      style={{
                        backgroundColor: this.state.contest
                          .contest_title_background_color
                      }}
                    >
                      <h4>{this.state.contest.contest_title}</h4>
                    </div>
                  </div>
                  <div className="row contest_image_div">
                    <img
                      src={api.image_path+this.state.contest.image}
                      className="contest_image"
                    />
                  </div>
                  <div className="user_birthdate">
                    <h4>{this.state.contest.contest_description}</h4>
                  </div>
                  <div className="user_birthdate_footer_div">
                    {this.state.user_birthdate && (
                      <div className="user_birthdate_datepicker_div">
                        <p className="ub_date">{this.state.user_birthdate}</p>
                        <a
                          onClick={() => {
                            isMobile
                              ? this.setState({ isOpen: true })
                              : this.refs.dp.focus();
                          }}
                        >
                          click to edit
                        </a>
                      </div>
                    )}
                    {!this.state.user_birthdate && (
                      <div className="row sharebtn_div user_birthdate_pare_div">
                        <p style={{ paddingBottom: 5 }}>
                          This contest requires additional information
                        </p>
                        {!isMobile && (
                          <div>
                            <p>Enter your date of birth</p>
                            <div style={{ display: "-webkit-box" }}>
                              <div style={{ display: "flex" }}>
                                <SelectField
                                  hintText="Day"
                                  // value={value}
                                  onChange={this.handleChangeDate.bind(this)}
                                  style={styles.ddm}
                                  className="userBirthdate_ddm"
                                  value={this.state.date}
                                >
                                  {date}
                                </SelectField>
                                <SelectField
                                  hintText="Month"
                                  // value={value}
                                  onChange={this.handleChangeMonth.bind(this)}
                                  style={styles.ddm1}
                                  value={this.state.month}
                                  className="userBirthdate_ddm"
                                >
                                  {months}
                                </SelectField>
                                <SelectField
                                  hintText="Year"
                                  // value={value}
                                  onChange={this.handleChangeYear.bind(this)}
                                  style={styles.ddm}
                                  value={this.state.year}
                                  className="userBirthdate_ddm"
                                >
                                  {years}
                                </SelectField>
                              </div>
                            </div>
                            <div className="row sharebtn_div user_birthdate_pare_div">
                              <button
                                onClick={() => {
                                  this.handleDone();
                                }}
                                className="btn_SocialShare user_birthdate_btn"
                              >
                                Done
                              </button>
                            </div>
                          </div>
                        )}
                        {this.state.show_error && (
                          <div className="bcd_shownotification_div">
                            <img
                              src={api.image_path+"error-msg-icon.png"}
                              alt="notify img"
                            />
                            <p className="notify_para">{this.state.error}</p>
                            <div className="bcd_shownotification_div1">
                              <a
                                onClick={() => {
                                  this.setState({ show_error: false });
                                }}
                                className="notify_para1"
                              >
                                X
                              </a>
                            </div>
                          </div>
                        )}
                        {isMobile && (
                          <button
                            onClick={() => {
                              isMobile
                                ? this.setState({ isOpen: true })
                                : this.refs.dp.focus();
                            }}
                            className="btn_SocialShare user_birthdate_btn"
                          >
                            Enter your date of birth
                          </button>
                        )}
                      </div>
                    )}
                    <DatePickerMaterial
                      hintText="Date"
                      className="dapi"
                      ref="dp"
                      style={{ display: "none" }}
                      //minDate={this.state.minDate}
                      maxDate={new Date()}
                      onChange={this.changeDate}
                    />
                    <div>
                      <DatePicker
                        showFormat="MM/DD/YYYY"
                        confirmText="Ok"
                        max={new Date()}
                        cancelText="Cancel"
                        value={this.state.time}
                        isOpen={this.state.isOpen}
                        onSelect={this.handleSelect}
                        onCancel={this.handleCancel}
                        theme="ios"
                        dateFormat={[
                          ["MM", month => monthMap[month]],
                          "DD",
                          "YYYY"
                        ]}
                      />
                    </div>
                    {this.state.user_birthdate && (
                      <div className="row sharebtn_div user_birthdate_pare_div">
                        <button
                          onClick={() => {
                            this.link_contest();
                          }}
                          className="btn_SocialShare user_birthdate_btn"
                        >
                          Done
                        </button>
                      </div>
                    )}
                    {!this.state.user_birthdate && (
                      <div className="row" style={{paddingTop:5}}>
                        <a className="user_birthdate_cancel"
                          onClick={() =>{
                            localStorage.setItem("current_state", "contest"),
                            this.props.history.push(
                              "/Contest/" +
                                localStorage.getItem("contest_id") +
                                "/" +
                                cookie.load("user_id")
                            )
                          }}
                          style={{ color: "black" }}
                        >
                          Cancel
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
        </center>
      </div>
    );
  }
}
const styles = {
  ddm: {
    background: "white",
    height: 45,
    width: 90,
    fontSize: 15,
    display: "block",
    position: "relative",
    paddingLeft: 10
  },
  ddm1: {
    background: "white",
    height: 45,
    width: 130,
    fontSize: 15,
    display: "block",

    position: "relative",
    paddingLeft: 10
  }
};
export default UserBirthDate;
