import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import InputMask from "react-input-mask";
import DatePicker from "react-datepicker";
import TimePicker from "react-time-picker";
import "react-datepicker/dist/react-datepicker.css";
import "./datepicker.scss";
import moment from "moment";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Card,
  Input,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  Button,
  Label,
  FormGroup,
  CustomInput,
} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";

import * as myConstClass from "../../constant.js";
import $ from "jquery";
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox,
} from "availity-reactstrap-validation";

class Validation extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    this.state = { checked: false };
     // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    this.handleCheckChange = this.handleCheckChange.bind(this);
    this.handleCheckChangeHourLeave =
      this.handleCheckChangeHourLeave.bind(this);
    // state = {
    //   startDate: new Date()
    // };
    this.state = {
      user_id: "0",
      units: "",
      org: "",
      emp: "",
      from_date: '',
      to_date: '',
      time: "10:00",
      timezones: "",
      full_day_leave: "",
      formData: {
        employee_id: "",
        from_date: Date.now(),
        to_date: Date.now(),
        leave_type_id: "",
        start_date_time: "",
        end_date_time: "",
        reason: "",
        status: "",
        total_days: "",
      },
      submitted: false,
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
    };

    this.options = {
      timeOut: parseInt(this.state.timeOut),
      showCloseButton: this.state.showCloseButton,
      progressBar: this.state.progressBar,
      position: this.state.position,
    };
  }

  handleChange = (event) => {
    const { formData } = this.state;
    formData[event.target.name] = event.target.value;
    this.setState({ formData });
  };
  handleCheckChange() {
    this.setState({
      checked: !this.state.checked,
    });
    this.setState({
      hourapply: !this.state.hourapply,
    });
  }
  handleCheckChangeHourLeave() {
    this.setState({
      hourchecked: !this.state.hourchecked,
    });

    this.setState({
      fullapply: !this.state.fullapply,
    });
  }

  // handleFromDateChange = (from_date) => {
  //   this.setState({ from_date });
  // };
  // handleToDateChange = to_date => {
  //   this.setState({ to_date });
  // };
  // handleFromDateChange = from_date => {
  //     this.setState({ from_date });
  // };

  // handleFromDateChange = (from_date) => {
  //   this.setState({ from_date });
  // };
  // handleToDateChange = (to_date) => {
  //   this.setState({ to_date });
  // };

  handleFromDateChange = (from_date) => {
    this.setState({ from_date });

    $("#spanfmbox").removeClass("is-invalid1");
    $("#spanfmlabel").css("color", "#3e4676");
    $("#spanfmbox").css("border-color", "hsl(0,0%,80%)");
    $("#spanfm").hide();
  };
  handleToDateChange = (to_date) => {
    this.setState({ to_date });
    $("#spantobox").removeClass("is-invalid1");
    $("#spantolabel").css("color", "#3e4676");
    $("#spantobox").css("border-color", "hsl(0,0%,80%)");
    $("#spanto").hide();
  };

  handleSubmit = (event, errors, values) => {
    //$('html, body').animate({ scrollTop: 0 }, 'fast');
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.from_date == undefined) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (this.state.to_date == null) {
        $("#spantobox").addClass("is-invalid1");
        $("#spantolabel").css("color", "#dc3545");
        $("#spantobox").css("border-color", "#dc3545");
        $("#spanto").show();
        window.scrollTo(0, 2000);
        i++;
        //return;
      }
    } else {
      if (
        this.state.from_date == undefined &&
        this.state.formData.from_date == undefined
      ) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (
        this.state.to_date == null &&
        this.state.formData.to_date == undefined
      ) {
        $("#spantobox").addClass("is-invalid1");
        $("#spantolabel").css("color", "#dc3545");
        $("#spantobox").css("border-color", "#dc3545");
        $("#spanto").show();
        window.scrollTo(0, 2000);
        i++;
        //return;
      }
    }
    if (errors) {
      return;
    }

    if (i !== 0) {
      return;
    }
  };

  routeChange() {
    this.props.history.push("/");
  }
  componentDidMount() {
   // window.googleTranslateElementInit = this.googleTranslateElementInit;
    // const google = window.google;
    // const script = document.createElement("script");
    // script.src =
    //   "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);

    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
    const answer_array = this.props.location.pathname.split("/");
    //alert(answer_array['3']);
    if (answer_array["3"]) {
      this.state.user_id = answer_array["3"];
      fetch(
        myConstClass.BASE_URL + "attendance/getLeaveInfo/" + answer_array["3"]
      )
        .then((response) => response.json())
        .then((response) => {
          if (response.full_day_leave == 1) {
            // this.setState({
            //   hourapply: true
            // })
            this.setState({
              checked: !this.state.checked,
            });
          }

          if (response.hour_day_leave == 1) {
            // this.setState({
            //   fullapply: true
            // })
            this.setState({
              hourchecked: !this.state.hourchecked,
            });
          }

          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }

    fetch(myConstClass.BASE_URL + "attendance/get_all_employees/" + admin_id)
      .then((response) => response.json())
      .then((response) => {
        this.setState({ emp: response });
      })
      .catch((err) => console.log(err));
  }
  // googleTranslateElementInit() {
  //   // / eslint-disable no-new /
  //   const google = window.google;
  //   new google.translate.TranslateElement(
  //     { pageLanguage: "en" },
  //     "google_translate_element_1"
  //   );
  //   new window.google.translate.TranslateElement(
  //     {
  //       pageLanguage: "pt",
  //       layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT,
  //     },
  //     "google_translate_element_1"
  //   );
  // }

  handleValidSubmit = () => {
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.from_date == undefined) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (this.state.to_date == null) {
        $("#spantobox").addClass("is-invalid1");
        $("#spantolabel").css("color", "#dc3545");
        $("#spantobox").css("border-color", "#dc3545");
        $("#spanto").show();
        window.scrollTo(0, 2000);
        i++;
        //return;
      }
    } else {
      if (
        this.state.from_date == undefined &&
        this.state.formData.from_date == undefined
      ) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (
        this.state.to_date == null &&
        this.state.formData.to_date == undefined
      ) {
        $("#spantobox").addClass("is-invalid1");
        $("#spantolabel").css("color", "#dc3545");
        $("#spantobox").css("border-color", "#dc3545");
        $("#spanto").show();
        window.scrollTo(0, 2000);
        i++;
        //return;
      }
    }
    if (i !== 0) {
      return;
    }
    this.setState({ submitted: true }, () => {
      const answer_array = this.props.location.pathname.split("/");
      var admin_id = localStorage.getItem("uname");
      setTimeout(() => this.setState({ submitted: false }), 5000);
      fetch(
        myConstClass.BASE_URL +
          `attendance/add_leave/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          body: JSON.stringify($("#pform").serializeArray()),
        }
      )
        .then((response) => response.json())
        .then((response) => {
          if (response == 3) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Leave Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Leave Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/leaves/listing");
          } else if (response == 2) {
            toastr.error("Error", "Please Select Leave ..!", this.options);
          } else if (response == 5) {
            toastr.error("Error", "Please Select From Date ..!", this.options);
          } else if (response == 6) {
            toastr.error("Error", "Please Select To Date ..!", this.options);
          } else if (response == 7) {
            toastr.error(
              "Error",
              "From Date should not be greater than To Date ..!",
              this.options
            );
          } else {
            toastr.error("Error", "Can not Add Leave ..!", this.options);
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, units, submitted } = this.state;
    const { emp } = this.state;
    var admin_id = localStorage.getItem("uname");
    // let start;
    // if( this.state.checked || formData.from_date_time != ''){
    //   start = null;
    // } else if(!this.state.checked){
    //   start= <AvGroup>
    // <Label for="example">Select Start Time</Label>
    // <AvField
    //         type="select"
    //         id="from_date_time"
    //         value={formData ? formData.from_date_time:this.state.from_date_time}
    //         onChange={this.handleChange}
    //         name="from_date_time"
    //         className="mb-3"
    //     >
    //         <option value=""></option>
    //         <option value="1">Starts in first half</option>
    //         <option value="2">Starts in second half</option>
    //         </AvField>
    // </AvGroup>
    // }
    const start =
      this.state.checked == "1" || this.state.hourchecked == "1" ? null : (
        <AvGroup>
          <Label for="example">Select Start Time</Label>
          <AvField
            type="select"
            id="from_date_time"
            value={
              formData ? formData.from_date_time : this.state.from_date_time
            }
            onChange={this.handleChange}
            name="from_date_time"
            className="mb-3"
          >
            <option value="">Select Duration</option>
            <option value="1">Starts in first half</option>
            <option value="2">Starts in second half</option>
          </AvField>
        </AvGroup>
      );

    const end =
      this.state.checked == "1" || this.state.hourchecked == "1" ? null : (
        <AvGroup>
          <Label for="example">Select End Time</Label>
          <AvField
            type="select"
            id="end_date_time"
            value={formData ? formData.end_date_time : this.state.end_date_time}
            onChange={this.handleChange}
            name="end_date_time"
            className="mb-3"
          >
            <option value="">Select Duration</option>
            <option value="1">Ends in first half</option>
            <option value="2">Ends in second half</option>
          </AvField>
        </AvGroup>
      );

    return (
      <Container fluid>
        <Header>
          <div id="google_translate_element_1"></div>
          <br />
          <HeaderTitle>
            {this.state.user_id !== "0" ? "Edit" : "Add"}
          </HeaderTitle>
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            <BreadcrumbItem>
              <Link to="/leaves/listing">Leave List</Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {this.state.user_id !== "0" ? "Edit" : "Add"}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          <CardBody>
            <AvForm
              id="pform"
              onSubmit={this.handleSubmit}
              onValidSubmit={this.handleValidSubmit}
            >
              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <label>
                      {" "}
                      Select Employee{" "}
                      <span style={{ color: "red", fontSize: "15px" }}>
                        {" "}
                        *
                      </span>{" "}
                    </label>
                    <AvField
                      type="select"
                      name="employee_id"
                      //label="Select Employee"
                      value={formData ? formData.employee_id : ""}
                      validate={{
                        required: {
                          value: true,
                          errorMessage: <div>Select Employee</div>,
                        },
                        // pattern: {value: '^[A-Za-z0-9]+$', errorMessage: 'Your name must be composed only with letter and numbers'},
                        // minLength: {value: 6, errorMessage: 'Your name must be between 6 and 16 characters'},
                        // maxLength: {value: 16, errorMessage: 'Your name must be between 6 and 16 characters'}
                      }}
                    >
                      <option value="">Select Employee</option>
                      {emp
                        ? emp.map((cell, i) => {
                            return (
                              <option value={cell.id}>
                                {cell.first_name} {cell.last_name}
                              </option>
                            );
                          })
                        : ""}
                    </AvField>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  {/* <AvGroup> */}
                  <Label for="example">From Date (YYYY-MM-DD)</Label>{" "}
                  <span style={{ color: "red", fontSize: "15px" }}> *</span>{" "}
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="from_date"
                      required
                     // minDate={moment().toDate()}
                      selected={this.state.from_date}
                      onChange={this.handleFromDateChange}
                      dateFormat="yyyy-MM-dd"
                      className="is-untouched is-pristine av-valid form-control"
                      style={{ width: "352px", height: "32px" }}
                      id="spanfmbox"
                      value={this.state.from_date || formData.from_date}
                    />
                  ) : (
                    <DatePicker
                      name="from_date"
                      required
                      //minDate={moment().toDate()}
                      selected={this.state.from_date}
                      className="is-untouched is-pristine av-valid form-control"
                      onChange={this.handleFromDateChange}
                      dateFormat="yyyy-MM-dd"
                      value={this.state.from_date}
                      id="spanfmbox"
                    />
                  )}
                  <span
                    id="spanfm"
                    style={{ color: "#dc3545", fontSize: "0.875em" }}
                    //style={this.state.showGalleryPlayButton}
                    style={{
                      display: "none",
                      fontSize: "0.875em",
                      color: "#dc3545",
                    }}
                    class="invalid-feedback11"
                  >Enter From Date</span>{" "}
                </Col>
              </Row>
              <Row>
                <Col lg={6}>
                  <Label for="example">To Date (YYYY-MM-DD)</Label>
                  <span style={{ color: "red", fontSize: "15px" }}>
                    {" "}
                    *
                  </span>{" "}
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="to_date"
                      required
                      selected={this.state.to_date}
                      onChange={this.handleToDateChange}
                      dateFormat="yyyy-MM-dd"
                      className="is-untouched is-pristine av-valid form-control"
                      style={{ width: "352px", height: "32px" }}
                      // value={formData ? formData.to_date:this.state.to_date}
                      // value={this.state.to_date || formData.to_date}
                      value={this.state.to_date || formData.to_date}
                      validate={{
                        required: {
                          value: true,
                          errorMessage: <div>Select Date</div>,
                        },
                      }}
                    />
                  ) : (
                    <DatePicker
                      name="to_date"
                      required
                      selected={this.state.to_date}
                      className="is-untouched is-pristine av-valid form-control"
                      onChange={this.handleToDateChange}
                      dateFormat="yyyy-MM-dd"
                      minDate={this.state.from_date ? this.state.from_date : ''}
                      value={this.state.to_date}
                      validate={{
                        required: {
                          value: true,
                          errorMessage: <div>Select Date</div>,
                        },
                      }}
                    />
                  )}
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Reason</Label>
                    <span style={{ color: "red", fontSize: "15px" }}>
                      {" "}
                      *
                    </span>{" "}
                    <AvInput
                      name="reason"
                      id="example"
                      required
                      value={formData ? formData.reason : ""}
                    />
                    <AvFeedback>Enter Reason</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <CustomInput
                    type="checkbox"
                    name="full_day_leave"
                    id="exampleCustomCheckbox"
                    label="Full Day Leave"
                    className="mb-2 select-checkbox"
                    checked={this.state.checked}
                    onChange={this.handleCheckChange}
                  />
                  {/* {(this.state.user_id !='0' && formData.from_date_time != '') ? 
             <CustomInput
                type="checkbox"
                name = "full_day_leave"
                id="exampleCustomCheckbox"
                label="Full Day Leave"
                className="mb-2"
                checked={ this.state.checked } 
                onChange={ this.handleCheckChange }
            /> :
            <CustomInput
            type="checkbox"
            name = "full_day_leave"
            id="exampleCustomCheckbox"
            label="Full Day Leave"
            defaultChecked
            className="mb-2"
            checked={ this.state.checked } 
            onChange={ this.handleCheckChange }
        />
      } */}
                </Col>
              </Row>
              <Row>
                <Col lg={6}> {start} </Col>
                <Col lg={6}>{end} </Col>
              </Row>

              <Row>
                <Col lg={6} style={{ zIndex: "0" }}>
                  <CustomInput
                    type="checkbox"
                    name="hourly_basis_leave"
                    id="exampleCustomCheckbox1"
                    label="Hourly Basis"
                    disabled={this.state.hourapply}
                    className="mb-2"
                    checked={this.state.hourchecked}
                    onChange={this.handleCheckChangeHourLeave}
                  />
                </Col>

                <Col
                  lg={6}
                  style={
                    this.state.hourchecked == true
                      ? { display: "block" }
                      : { display: "none" }
                  }
                >
                  <AvGroup>
                    <Label for="example">Hours</Label>

                    <AvField
                      type="select"
                      value={
                        formData ? formData.hour_leave : this.state.hour_leave
                      }
                      // onChange={this.handleChange}
                      name="hour_leave"
                      className="mb-3"
                    >
                      <option value="0.5">0.5</option>
                      <option value="1">1.0</option>
                      <option value="1.5">1.5</option>

                      <option value="2">2.0</option>
                      <option value="2.5">2.5</option>
                      <option value="3">3.0</option>

                      <option value="3.5">3.5</option>
                      <option value="4">4.0</option>
                      <option value="4.5">4.5</option>

                      <option value="5">5.0</option>
                      <option value="5.5">5.5</option>
                      <option value="6">6.0</option>

                      <option value="6.5">6.5</option>
                      <option value="7">7.0</option>
                      <option value="7.5">7.5</option>

                      <option value="8">8.0</option>
                      <option value="8.5">8.5</option>
                      <option value="9">9.0</option>

                      <option value="9.5">9.5</option>
                      <option value="10">10.0</option>
                      <option value="10.5">10.5</option>

                      <option value="11">11.0</option>
                      <option value="11.5">11.5</option>
                      <option value="12">12.0</option>
                    </AvField>
                  </AvGroup>
                </Col>
              </Row>

              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Select Leave</Label>
                    <AvField
                      type="select"
                      id="leave_type_id"
                      value={
                        formData
                          ? formData.leave_type_id
                          : this.state.leave_type_id
                      }
                      name="leave_type_id"
                      className="mb-3"
                    >
                      <option value="1">Annual Leave</option>
                      <option value="2">Sick Leave</option>
                      <option value="3">Family Leave</option>
                      <option value="4">Maternal Leave</option>
                      <option value="5">Paternal Leave</option>
                      <option value="6">Other</option>
                    </AvField>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Status</Label>
                    <AvField
                      type="select"
                      id="status"
                      value={formData ? formData.status : this.state.status}
                      onChange={this.handleChange}
                      name="status"
                      className="mb-3"
                    >
                      <option value="1">Pending</option>
                      <option value="2">Approved</option>
                      <option value="3">Rejected</option>
                    </AvField>
                  </AvGroup>
                </Col>
              </Row>
              <br />
              <br />
              <FormGroup>
                <Link
                  to="/leaves/listing"
                  style={{
                    margin: "0rem 1.50rem 1.50rem 0rem",
                    border: "#6f42c1 1px solid",
                    color: "#6f42c1",
                    padding: "0.10rem 0.90rem 0.30rem 0.90rem",
                    textDecoration: "none",
                    borderRadius: "0.2rem",
                  }}
                >
                  Cancel
                </Link>
                {this.state.user_id != "0" ? (
                  <Button disabled={submitted}>
                    {(submitted && "Your form is submitted!") ||
                      (!submitted && "Update")}
                  </Button>
                ) : (
                  <Button disabled={submitted}>
                    {(submitted && "Your form is submitted!") ||
                      (!submitted && "Add")}
                  </Button>
                )}
              </FormGroup>
            </AvForm>
          </CardBody>
        </Card>
      </Container>
    );
  }
}

export default Validation;
