import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./datepicker.scss";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Card,
  CardBody,
  Container,
  Button,
  Label,
  FormGroup,
} 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 {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
} from "availity-reactstrap-validation";

class Validation extends PureComponent {
  constructor(props) {
    super(props);
     // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    this.routeChange = this.routeChange.bind(this);
    this.onInTimeChange = this.onInTimeChange.bind(this);
    // state = {
    //   startDate: new Date()
    // };
    this.state = {
      user_id: "0",
      units: "",
      org: "",
      emp: "",
      startDate: new Date(),
      clock_in: "",
      clock_out: "",
      timezones: "",
      attendance_date: Date.now(),
      formData: {
        employee_id: "",
        attendance_date: "",
        clock_in: "",
        clock_out: "",
        timezone: "",
      },
      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,
    };
  }
  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/getAttendanceInfoE/" +
          answer_array["3"]
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }

    var admin_id = localStorage.getItem("uname");
    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"
  //   );
  // }
  handleChange = (attendance_date) => {
    this.setState({ attendance_date });
    if (attendance_date) {
      $("#spanfmbox").removeClass("is-invalid1");
      $("#spanfmlabel").css("color", "#3e4676");
      $("#spanfmbox").css("border-color", "hsl(0,0%,80%)");
      $("#spanfm").hide();
    } else {
      $("#spanfmbox").addClass("is-invalid1");
      $("#spanfmlabel").css("color", "#dc3545");
      $("#spanfmbox").css("border-color", "#dc3545");
      $("#spanfm").show();
    }
  };

  handleSubmit = (event, errors, values) => {
    //$('html, body').animate({ scrollTop: 0 }, 'fast');
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.attendance_date == undefined) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (this.state.attendance_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.attendance_date == undefined &&
        this.state.formData.attendance_date == undefined
      ) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
     
    }
    if (errors) {
      return;
    }

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

  onInTimeChange = (clock_in) => this.setState({ clock_in });
  onOutTimeChange = (clock_out) => this.setState({ clock_out });
  // handleChange = date => {
  //   this.setState({
  //     startDate: date
  //   });
  // };

  handleValidSubmit = () => {
    var admin_id = localStorage.getItem("uname");
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.attendance_date == undefined) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
      if (this.state.attendance_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.attendance_date == undefined &&
        this.state.formData.attendance_date == undefined
      ) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
  
    }

    if (i !== 0) {
      return;
    }
    this.setState({ submitted: true }, () => {
      setTimeout(() => this.setState({ submitted: false }), 5000);
      fetch(
        myConstClass.BASE_URL +
          `attendance/add_attendance/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          body: JSON.stringify($("#pform").serializeArray()),
        }
      )
        .then((response) => response.json())
        .then((response) => {
          if (response == 4) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Attendance Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Attendance Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/attendance/listing");
          } else if (response == 2) {
            toastr.error("Error", "Please enter In time ..!", this.options);
          } else if (response == 3) {
            toastr.error("Error", "Please enter Out time ..!", this.options);
          } else {
            toastr.error("Error", "Can not Add Attendance ..!", this.options);
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, units, submitted } = this.state;
    const { emp } = this.state;
    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="/employee/listing">Attendance List</Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {this.state.user_id !== "0" ? "Edit" : "Add"}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          {/* <CardHeader>
              <CardTitle tag="h5">Availity Validation</CardTitle>
              <h6 className="card-subtitle text-muted">
                Form validation by availity-reactstrap-validation
              </h6>
            </CardHeader> */}
          <CardBody>
            <AvForm
              id="pform"
              onValidSubmit={this.handleValidSubmit}
              onSubmit={this.handleSubmit}
            >
              {/* With AvGroup AvInput and AvFeedback to build your own */}
              <Row>
                <Col lg={6}>
                  <AvGroup>
                    {/* <AvInput name="employee_id" id="example" required value={formData ? formData.employee_id:''}/>
                  <AvFeedback>Enter Employee ID!</AvFeedback> */}
                    <label>Select Employee</label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvField
                      type="select"
                      name="employee_id"
                      // label="Select Employee"
                      required
                      value={formData ? formData.employee_id : ""}
                    >
                      <option disabled={true} value="">
                        Select Employee
                      </option>
                      {emp
                        ? emp.map((cell, i) => {
                            return (
                              <option value={cell.id}>
                                {cell.first_name} {cell.last_name}
                              </option>
                            );
                          })
                        : ""}
                    </AvField>
                    <AvFeedback>Enter Employee</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  {/* <AvGroup> */}
                  <Label id="spanfmlabel" for="example">
                    Attendance Date (YYYY-MM-DD)
                  </Label>
                  <span style={{ color: "red", fontSize: "15px" }}> *</span>
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="attendance_date"
                      selected={this.state.attendance_date}
                      onChange={this.handleChange}
                      dateFormat="dd-MM-yyyy"
                      id="spanfmbox"
                      className="is-untouched is-pristine av-valid form-control"
                      style={{ width: "352px", height: "32px" }}
                      value={
                        formData
                          ? formData.attendance_date
                          : this.state.attendance_date
                      }
                    />
                  ) : (
                    <DatePicker
                      name="attendance_date"
                      selected={this.state.attendance_date}
                      id="spanfmbox"
                      className="is-untouched is-pristine av-valid form-control"
                      onChange={this.handleChange}
                      dateFormat="dd-MM-yyyy"
                      value={this.state.attendance_date}
                    />
                  )}
                  <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 Date
                  </span>
                </Col>

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">In-Time</Label>
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="clock_in"
                      type="time"
                      value={formData ? formData.clock_in : ""}
                      required
                    />
                    <AvFeedback>Enter In-Time</AvFeedback>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                  {/* <AvGroup> */}
                  <Label for="example">Out-Time</Label>
                  <AvInput
                    name="clock_out"
                    type="time"
                    value={formData ? formData.clock_out : ""}
                  />
                  {/* </AvGroup> */}
                </Col>

                {/* <Col lg={6}>
              
                <Label for="example">In-Time</Label> <br/>
                {(this.state.user_id !='0' ) ? <TimePicker
                name="clock_in"           
                onChange={this.onInTimeChange}
                value={ this.state.clock_in || formData.clock_in}
               />
               :
               <TimePicker
                name="clock_in"             
                onChange={this.onInTimeChange}
                value={this.state.clock_in}
               /> }  
             </Col>   
             <Col lg={6}>
               
                <Label for="example">Out-Time</Label> <br/>
                {(this.state.user_id !='0' ) ?  <TimePicker
                name="clock_out"          
                onChange={this.onOutTimeChange}
                value={this.state.clock_out || formData.clock_out}
               /> 
               :
               <TimePicker
                name="clock_out"         
                onChange={this.onOutTimeChange}
                value={this.state.clock_out}
               /> }  
             </Col>         */}
              </Row>
              <br />

              <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Attendance Notes</Label>
                    <AvInput
                      name="attendanceNotes"
                      id="example"
                      type="textarea"
                      value={formData ? formData.attendanceNotes : ""}
                    />
                    {/* <AvFeedback>Enter Attendance Notes</AvFeedback> */}
                  </AvGroup>
                </Col>

                {/* <Col lg={6}>
                 <AvField
                  type="select"
                  name="unit"
                  label="Unit"
                  value={formData ? formData.unit:''}
                >
                  {units ?  units.map((cell, i) => {
                  return(<option value={cell.id}>{cell.name}({cell.symbol})</option>)
                  }) : ''}       
                </AvField>
                </Col> */}
              </Row>
              <br />
              <br />
              {/* <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">Sequence</Label>
                  <AvInput name="sequence" value={formData ? formData.sequence:''} id="example" validate={{
                  required: {value: true},
                  pattern: {value: '^[0-9]+$'},
                  
                }} />
                  <AvFeedback>Enter Number</AvFeedback>
                </AvGroup>
                </Col>
                </Row> */}

              <FormGroup>
                <Link
                  to="/attendance/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;
