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 ReactQuill from "react-quill";
import dateFormat from "dateformat";
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.handleCheckChange=this.handleCheckChange.bind(this);
     // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    // state = {
    //   startDate: new Date()
    // };
    this.state = {
      user_id: "0",
      units: "",
      org: "",
      emp: "",
      date:'',
      startDate: new Date(),
      time: "10:00",
      timezones: "",
      formData: {
        employee_id: "",
        date: "",
        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,
    };
  }
  preventKeyboardInteraction = (event) => {
    event.preventDefault();
  }

  handleTextChange = (announcement) => {
    this.setState({ announcement });
  };
  handleCheckChange() {
    this.setState({
      checked: !this.state.checked,
    });
  }
  handleChange = (date) => {
    this.setState({ date });
    if (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) => {
    //alert(this.state.date);
    //$('html, body').animate({ scrollTop: 0 }, 'fast');
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.date == undefined || this.state.date == "") {
        //alert('hii');
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
    } else {
      if (
        this.state.date == undefined &&
        this.state.formData.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;
    }
  };

  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 +
          "organization/getHolidayInfo/" +
          answer_array["3"]
      )
        .then((response) => response.json())
        .then((response) => {
   

          if (response.is_apply_schduler == 1) {
            this.setState({
              checked: !this.state.checked,
            });
          }


          this.setState({ formData: response });
        })
        .catch((err) => console.log(err));
    }
    var admin_id = localStorage.getItem("uname");


    fetch(
      myConstClass.BASE_URL + "organization/get_all_organizations/" + admin_id
    )
      .then((response) => response.json())
      .then((response) => {
        this.setState({ organization: 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 admin_id = localStorage.getItem("uname");
    var i = 0;
    if (this.state.user_id == "0") {
      if (this.state.date == undefined) {
        $("#spanfmbox").addClass("is-invalid1");
        $("#spanfmlabel").css("color", "#dc3545");
        $("#spanfmbox").css("border-color", "#dc3545");
        $("#spanfm").show();
        i++;
        //return;
      }
    } else {
      if (
        this.state.date == undefined &&
        this.state.formData.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 +
          `organization/add_public_holiday/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          method: "POST",
          body: JSON.stringify($("#pform").serializeArray()),
          // contentType: "application/json; charset=utf-8",
        }
      )
        .then((response) => response.json())
        .then((response) => {
          if (response == true) {
            this.state.user_id == "0"
              ? toastr.success(
                  "Success",
                  "Holiday Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  "Success",
                  "Holiday Updated Successfully..!",
                  this.options
                );

            this.props.history.push("/settingsholidays/listing");
          } else {
            toastr.error("Error", "Can not Add Holiday ..!", this.options);
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, units, submitted,organization } = this.state;
    let date;
    if (this.state.user_id !== "0") {
      date = formData.date;
    } else {
      date = this.state.date;
    }

    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="/settingsholidays/listing">Public Holidays 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>
                    {/* <AvInput name="employee_id" id="example" required value={formData ? formData.employee_id:''}/>
                  <AvFeedback>Enter Employee ID!</AvFeedback> */}
                    <AvField
                      type="select"
                      name="organization_id"
                      required
                      label="Select Organization"
                      value={formData ? formData.organization_id : ""}
                    >
                      <option value="">Select Organization</option>
                      {organization
                        ? organization.map((cell, i) => {
                            return (
                              <option value={cell.id}>{cell.title}</option>
                            );
                          })
                        : ""}
                    </AvField>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Name</Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <AvInput
                      name="name"
                      id="example"
                      required
                      value={formData ? formData.name : ""}
                    />
                    <AvFeedback>Enter Holiday Name !</AvFeedback>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label id="spanfmlabel" for="example">
                      Date (DD/MM/YYYY)
                    </Label>{" "}
                    <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    <br />
                    {this.state.user_id != "0" ? (
                      <DatePicker
                        name="date"
                        selected={this.state.date}
                        onChange={this.handleChange}
                        //dateFormat="dd-mm-yyyy"
                        showYearDropdown
                        // disabled
                        yearDropdownItemNumber={15}
                        scrollableYearDropdown
                        className="is-untouched is-pristine av-valid form-control"
                        dateFormat="dd-MM-yyyy"
                        // style={{width: '352px',height:'32px'}}
                        value={this.state.date || formData.date}
                        
                        id="spanfmbox"
                        onKeyDown={this.preventKeyboardInteraction}
                      />
                    ) : (
                      <DatePicker
                        name="date"
                        selected={this.state.date}
                        onChange={this.handleChange}
                        showYearDropdown
                        // disabled
                        yearDropdownItemNumber={15}
                        scrollableYearDropdown
                        className="is-untouched is-pristine av-valid form-control"
                        dateFormat="dd-MM-yyyy"
                        value={this.state.date}
                        id="spanfmbox"
                        onKeyDown={this.preventKeyboardInteraction}
                      />
                    )}
                    <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>
                  </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Select Status<span style={{ color: "red", fontSize: "15px" }}> *</span></Label>
                    <AvField
                      type="select"
                      value={formData ? formData.status : "1"}
                      name="status"
                      className="mb-3"
                      
                    >
                       {/* <option disabled={true} >Select Status</option> */}
                      <option value="1">Active</option>
                      <option value="2">In-Active</option>
                    </AvField>
                  </AvGroup>
                </Col>
              </Row>
              <Row>
              <Col lg={6}>
                  <Label for="example">
                   Apply Shift
                  </Label>

                  <CustomInput
                    type="checkbox"
                    name="is_apply_schduler"
                    id="exampleCustomCheckbox"
                   // label={TF("{0} {1}", T("Apply"), T("Shift"))}
                    className="mb-2"
                    checked={this.state.checked}
                    onChange={this.handleCheckChange}
                  />
                </Col>
                
              </Row>
              <FormGroup>
                <Link
                  to="/settingsholidays/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;
