import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import DatePicker from "react-datepicker";
import moment from "moment";
//import './bulk_import.scss';
import dateFormat from "dateformat";
//import TimePicker from 'react-time-picker';
import "react-datepicker/dist/react-datepicker.css";
// import './datepicker.scss';
import Select from "react-select";
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 {
  AvInput,
  AvForm,
  AvField,
  AvGroup,
  AvFeedback,
} from "availity-reactstrap-validation";

import { T, Config, TF } from "react-translator-component";
Config.default = localStorage.getItem("lang");

class Validation extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    this.state = { checked: false };
    this.handleCheckChange = this.handleCheckChange.bind(this);
    // state = {
    //   startDate: new Date()
    // };
    this.state = {
      user_id: "0",
      units: "",
      org: "",
      emp: "",
      startDate: new Date(),
      in_time: "10:00",
      timezones: "",
      full_day_leave: "",
      formData: {
        employee_id: "",
        date: Date.now(),
        to_date: Date.now(),
        leave_type_id: "",
        start_date_time: "",
        end_date_time: "",
        reason: "",
        status: "",
        total_days: "",
        //	pay_code:'',
        employee_shift: "",
      },
      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,
    };
  }

  onInTimeChange = (in_time) => {
    //alert(in_time);
    this.setState({ in_time: in_time });
    $(".in_time")
      .children(".react-time-picker__wrapper")
      .css("border-color", "hsl(0,0%,80%)");
    $("#in_time").hide();
  };
  // onInTimeChange = clock_in => this.setState({ clock_in })
  onOutTimeChange = (out_time) => {
    this.setState({ out_time });
    $(".out_time")
      .children(".react-time-picker__wrapper")
      .css("border-color", "hsl(0,0%,80%)");
    $("#out_time").hide();
  };

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

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

  handleFromDateChange = (date) => {
    this.setState({ attendance_record_date: date });

    if (date != null) {
      $("#spanfmdatebox").removeClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#3e4676");
      $("#spanfmdatebox").css("border-color", "hsl(0,0%,80%)");
      $("#spanfmdate").hide();
    } else {
      $("#spanfmdatebox").addClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#dc3545");
      $("#spanfmdatebox").css("border-color", "#dc3545");
      $("#spanfmdate").show();
    }
  };

  handleOTDateChange = (date) => {
    this.setState({ ot_date: date });

    if (date != null) {
      $("#spanfmdatebox").removeClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#3e4676");
      $("#spanfmdatebox").css("border-color", "hsl(0,0%,80%)");
      $("#spanfmdate").hide();
    } else {
      $("#spanfmdatebox").addClass("is-invalid1");
      $("#spanfmdatelabel").css("color", "#dc3545");
      $("#spanfmdatebox").css("border-color", "#dc3545");
      $("#spanfmdate").show();
    }
  };

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

  routeChange() {
    this.props.history.push("/");
  }
  componentDidMount() {
    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
    const answer_array = this.props.location.pathname.split("/");
    //alert(this.props.location.state._id);
    if (answer_array) {
      this.state.user_id = this.props.location.state._id;
      // if (this.props.location.state._id != '0') {
      //   //  alert(days);
      //   $("#employee_id").addClass("pointerEventNone");
      //   $("#employee_id").removeClass("pointerEventNone1");
      // }
      // else {
      //   $("#employee_id").removeClass("pointerEventNone");
      //   $("#employee_id").addClass("pointerEventNone1");
      // }

      // this.state.user_id = answer_array['5'];
      // if (this.props.location.state._id1 == '0') {
      fetch(
        myConstClass.BASE_URL +
          "user/getEmployeeIssueInfo/" +
          this.state.user_id
      )
        .then((response) => response.json())
        .then((response) => {
          //this.setState({employee_shift:[{ value:response.employee_id, label:response.emp_name }]});
          // if (this.state.user_id != '0') {
          //   this.setState({ employee_shift: [{ value: response.shift_id, label: response.emp_shift }] });
          //   this.setState({ pay_code: [{ value: response.pay_code, label: response.paycode_name }] });
          // }

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

      fetch(myConstClass.BASE_URL + "user/getTicketCategory/" + admin_id)
        //fetch(myConstClass.BASE_URL+url)
        .then((response) => response.json())
        .then((response) => {
          this.setState({ ticketcategory: response });
        })
        .catch((err) => console.log(err));
      // }
      // else {

      // }
    }

    var login_type = localStorage.getItem("login_type");
    var login_id = localStorage.getItem("login_id");
    if (login_type != "emp") {
      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));
    } else {
      fetch(
        myConstClass.BASE_URL +
          "attendance/get_all_employees/" +
          admin_id +
          "/" +
          login_id
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ emp: response });
        })
        .catch((err) => console.log(err));
    }
  }

  handleSubmit = (event, errors) => {
    // if(this.state.employee_shift==null)
    // {
    //   $("#selectIDE1").addClass("is-invalid1");
    //   $("#selectIDElabel1").css("color", "#dc3545");
    //   $("#selectIDE1").children(".css-yk16xz-control").css( "border-color", "#dc3545" );
    //   $("#selectIDEs1").show();
    //  i++;
    //  //return;
    // }

    if (errors) {
      return;
    }

    // if (i !== 0) {

    //   return;
    // }
  };

  handleValidSubmit = () => {
    var i = 0;

    if (i !== 0) {
      return;
    }
    this.setState({ submitted: true }, () => {
      var login_type = localStorage.getItem("login_type");
      var admin_id = localStorage.getItem("uname");
      //setTimeout(() => this.setState({ submitted: false }), 5000);
      fetch(
        myConstClass.BASE_URL +
          `attendance/add_issue/` +
          admin_id +
          "/" +
          this.state.user_id +
          "/" +
          login_type,
        {
          method: "POST",
          body: JSON.stringify($("#pform").serializeArray()),
        }
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ submitted: false });
          if (response) {
            this.state.user_id == "0"
              ? toastr.success(
                  TF("{0}", T("Success")),
                  TF("{0}", T(myConstClass.ADDMSG)),
                  this.options
                )
              : toastr.success(
                  TF("{0}", T("Success")),
                  TF("{0}", T(myConstClass.UPDATEMSG)),
                  this.options
                );

            this.props.history.push("/" + "employeesissues/listing");
          } else {
            toastr.error(
              TF("{0}", T("Error")),
              TF("{0}", T(myConstClass.ERRORMSG)),
              this.options
            );
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, submitted, ticketcategory } = this.state;
    const { emp } = this.state;

    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
            {this.state.user_id != "0" ? T("Edit") : T("Add")}
          </HeaderTitle>
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to={"/" + "dashboard"}>{T("Dashboard")}</Link>
            </BreadcrumbItem>
            <BreadcrumbItem>
              <Link to={"/" + "employeesissues/listing"}>
                {" "}
                Employee Request
              </Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {this.state.user_id != "0" ? T("Edit") : T("Add")}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          <CardBody>
            <AvForm
              id="pform"
              onSubmit={this.handleSubmit}
              onValidSubmit={this.handleValidSubmit}
            >
              <h4>
                Employee Request
                <span
                  style={{ color: "red", fontSize: "14px", float: "right" }}
                >
                  {" "}
                  {T("All fields marked with * are required")}{" "}
                </span>
              </h4>
              <hr />
              <Row>
                {this.state.user_id != "0" ? (
                  <Col lg={6}>
                    <AvGroup>
                      <Label for="example">
                        {TF("{0} {1}", T("Ticket"), T("No"))}

                        <span style={{ color: "red", fontSize: "15px" }}>
                          {" "}
                          *
                        </span>
                      </Label>
                      <AvInput
                        name="ticket_no"
                        id="example"
                        type="text"
                        required
                        readOnly
                        value={formData ? formData.ticket_no : ""}
                      />
                      <AvFeedback>
                        {" "}
                        {TF("{0} {1} {2}!", T("Enter"), T("In"), T("Time"))}
                      </AvFeedback>
                    </AvGroup>
                  </Col>
                ) : (
                  ""
                )}
                <Col lg={6}>
                  <Label for="example">
                    {T("Select")} {T("Employee")}{" "}
                  </Label>
                  <span style={{ color: "red", fontSize: "15px" }}> *</span>
                  <AvGroup>
                    {this.state.user_id != "0" ? (
                      <AvField
                        style={
                          this.state.user_id != "0"
                            ? { PointerEvent: "none" }
                            : { cursor: "Pointer" }
                        }
                        type="select"
                        id="employee_id"
                        className="is-untouched is-pristine av-valid pointerEventNone"
                        name="employee_id"
                        // style={this.state.user_id != '0' ? { PointerEvent: 'none' } : { cursor: 'Pointer' }}
                        // label=" Employee"
                        //onChange={this.dep_change}
                        value={formData ? formData.employee_id : ""}
                        readOnly={this.state.user_id != "0" ? true : false}
                        required
                      >
                        <option readOnly="true">
                          {T("Select")} {T("Employee")}
                        </option>
                        {emp
                          ? emp.map((cell) => {
                              return (
                                <option value={cell.id}>
                                  {cell.status} {cell.first_name}{" "}
                                  {cell.last_name}
                                </option>
                              );
                            })
                          : ""}
                      </AvField>
                    ) : (
                      <AvField
                        type="select"
                        id="employee_id"
                        // className="is-untouched is-pristine av-valid pointerEventNone1"
                        name="employee_id"
                        // style={this.state.user_id != '0' ? { PointerEvent: 'none' } : { cursor: 'Pointer' }}
                        // label=" Employee"
                        //onChange={this.dep_change}
                        value={formData ? formData.employee_id : ""}
                        readOnly={this.state.user_id != "0" ? true : false}
                        required
                      >
                        <option disabled="true">
                          {T("Select")} {T("Employee")}
                        </option>
                        {emp
                          ? emp.map((cell) => {
                              return (
                                <option value={cell.id}>
                                  {cell.status} {cell.first_name}{" "}
                                  {cell.last_name}
                                </option>
                              );
                            })
                          : ""}
                      </AvField>
                    )}
                    <AvFeedback>
                      {" "}
                      {T("Enter")} {T("Employee")}
                    </AvFeedback>
                  </AvGroup>
                </Col>
              </Row>

              <br />

              <Row>
                <Col lg={6}>
                  <AvGroup>
                    {/* <label id="selectIDElabel"> {TF("{0} {1}", T("Ot"),T("Type"))}</label><span style={{ color: 'red', fontSize: '15px' }}> *</span> */}
                    <AvField
                      type="select"
                      name="ticket_category"
                      label={TF("{0} {1}", T("Ticket"), T("Category"))}
                      value={formData ? formData.ticket_category : ""}
                    >
                      {/* <option value="0">30%</option>
                      <option value="1">150%</option>
                      <option value="1">200%</option> */}
                      <option value="0">
                        {TF("{0} {1}", T("Select"), T("Category"))}{" "}
                      </option>
                      {ticketcategory
                        ? ticketcategory.map((cell) => {
                            return <option value={cell.id}>{cell.type}</option>;
                          })
                        : ""}
                    </AvField>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">
                      {TF("{0} {1}", T("Employee"), T("Remark"))}
                    </Label>
                    <AvInput
                      type="textarea"
                      name="employee_remark"
                      id="example"
                      required
                      value={formData ? formData.employee_remark : ""}
                    />
                    <AvFeedback>
                      {TF(
                        "{0} {1} ...!",
                        T("Enter"),
                        T("Employee"),
                        T("Remark")
                      )}
                    </AvFeedback>
                  </AvGroup>
                </Col>
              </Row>
              {this.state.user_id != "0" ? (
                <Row>
                  <Col lg={6}>
                    <AvGroup>
                      <Label for="example">
                        {TF("{0} {1}", T("Hr"), T("Remark"))}
                      </Label>
                      <AvInput
                        type="textarea"
                        name="hr_remark"
                        id="example"
                        value={formData ? formData.hr_remark : ""}
                      />
                      {/* <AvFeedback>{TF("{0} {1} ...!", T("Enter"), T("HR"),T("Remark"))}</AvFeedback> */}
                    </AvGroup>
                  </Col>

                  <Col lg={6}>
                    <AvGroup>
                      {/* <label id="selectIDElabel"> {TF("{0} {1}", T("Ot"),T("Type"))}</label><span style={{ color: 'red', fontSize: '15px' }}> *</span> */}
                      <AvField
                        type="select"
                        name="status"
                        label={TF("{0}", T("Status"))}
                        value={formData ? formData.status : ""}
                      >
                        <option disabled={true} value="">
                          {" "}
                          {T("Select")}
                        </option>
                        <option value="1">{T("Pending")}</option>
                        <option value="2">{T("In Progress")}</option>
                        <option value="3">{T("Resolved")}</option>
                        {/* <option value="1">WorkzonePro</option> */}
                      </AvField>
                    </AvGroup>
                  </Col>
                </Row>
              ) : (
                ""
              )}
              <FormGroup>
                <Link
                  to={"/" + "employeesissues/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",
                  }}
                >
                  {T("Cancel")}
                </Link>
                {this.state.user_id != "0" ? (
                  <Button disabled={submitted}>
                    {(submitted &&
                      TF(
                        "{0} {1} {2} {3}!",
                        T("Your"),
                        T("form"),
                        T("is"),
                        T("submitted")
                      )) ||
                      (!submitted && T("Update"))}
                  </Button>
                ) : (
                  <Button disabled={submitted}>
                    {(submitted &&
                      TF(
                        "{0} {1} {2} {3}!",
                        T("Your"),
                        T("form"),
                        T("is"),
                        T("submitted")
                      )) ||
                      (!submitted && T("Add"))}
                  </Button>
                )}
              </FormGroup>
            </AvForm>
          </CardBody>
        </Card>
      </Container>
    );
  }
}

export default Validation;
