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({ 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 +
            "shifts/getShiftScdeuleInfo/" +
            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 });

            fetch(
              myConstClass.BASE_URL +
                "user/getLeavesBalance/" +
                admin_id +
                "/" +
                response.employee_id
            )
              .then((response) => response.json())
              .then((response) => {
                this.setState({ current_bal: response });
              })
              .catch((err) => console.log(err));

            fetch(
              myConstClass.BASE_URL +
                "shifts/getShiftScheduletime/" +
                response.shift_id +
                "/" +
                response.date
            )
              .then((response) => response.json())
              .then((response) => {
                //alert(response);
                // ("#shifttime").text(response);
                this.setState({ shifttime: response });
              })
              .catch((err) => console.log(err));
          })
          .catch((err) => console.log(err));
      } else {
        fetch(
          myConstClass.BASE_URL +
            "shifts/getShiftScdeuleInfoAdjust/" +
            this.state.user_id +
            "/" +
            this.props.location.state._id1
        )
          .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 });

            fetch(
              myConstClass.BASE_URL +
                "user/getLeavesBalance/" +
                admin_id +
                "/" +
                response.employee_id
            )
              .then((response) => response.json())
              .then((response) => {
                this.setState({ current_bal: response });
              })
              .catch((err) => console.log(err));

            fetch(
              myConstClass.BASE_URL +
                "shifts/getShiftScheduletime/" +
                response.shift_id +
                "/" +
                response.date
            )
              .then((response) => response.json())
              .then((response) => {
                //alert(response);
                // ("#shifttime").text(response);
                this.setState({ shifttime: response });
              })
              .catch((err) => console.log(err));
          })
          .catch((err) => console.log(err));
      }

      fetch(myConstClass.BASE_URL + "shifts/getPayCodes/" + admin_id)
        .then((response) => response.json())
        .then((response) => {
          this.setState({ pay_codes: response });
        })
        .catch((err) => console.log(err));

      fetch(myConstClass.BASE_URL + "shifts/getShifts/" + admin_id + "/0/0/0")
        .then((response) => response.json())
        .then((response) => {
          this.setState({ shifts: 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));
    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_schdule/" +
          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_emplogin/" +
          admin_id +
          "/" +
          login_id
      )
        .then((response) => response.json())
        .then((response) => {
          this.setState({ emp: response });
        })
        .catch((err) => console.log(err));
    }
  }

  PayCodeChange = (pay_code) => {
    this.setState({ pay_code: pay_code });

    if (pay_code != null) {
      $("#selectIDE").removeClass("is-invalid1");
      $("#selectIDElabel").css("color", "#3e4676");
      $("#selectIDE")
        .children(".css-1pahdxg-control")
        .css("border-color", "hsl(0,0%,80%)");
      $("#selectIDEs").hide();
    } else {
      $("#selectIDE").addClass("is-invalid1");
      $("#selectIDElabel").css("color", "#dc3545");
      $("#selectIDE")
        .children(".css-yk16xz-control")
        .css("border-color", "#dc3545");
      $("#selectIDEs").show();
    }
  };

  handleShiftChange = (shift) => {
    this.setState({ employee_shift: shift });
    if (shift != null) {
      $("#selectIDE1").removeClass("is-invalid1");
      $("#selectIDElabel1").css("color", "#3e4676");
      $("#selectIDE1")
        .children(".css-1pahdxg-control")
        .css("border-color", "hsl(0,0%,80%)");
      $("#selectIDEs1").hide();
    } else {
      $("#selectIDE1").addClass("is-invalid1");
      $("#selectIDElabel1").css("color", "#dc3545");
      $("#selectIDE1")
        .children(".css-yk16xz-control")
        .css("border-color", "#dc3545");
      $("#selectIDEs1").show();
    }

    let x = Object.values(shift);
    // this.dep_id = event.target.value;
    this.dep_id = x[0];

    var tdate = dateFormat(this.state.date, "yyyy-mm-dd");

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShiftScheduletime/" +
        this.dep_id +
        "/" +
        tdate
    )
      .then((response) => response.json())
      .then((response) => {
        //alert(response);
        // ("#shifttime").text(response);
        this.setState({ shifttime: response });
      })
      .catch((err) => console.log(err));
  };

  handleSubmit = (event, errors) => {
    //alert(this.state.pay_code);
    //$('html, body').animate({ scrollTop: 0 }, 'fast');
    var i = 0;
    // if(this.state.date==undefined)
    //   {
    //     $("#spanfmdatebox").addClass("is-invalid1");
    //     $("#spanfmdatelabel").css("color", "#dc3545");
    //     $("#spanfmdatebox").css( "border-color", "#dc3545" );
    //     $("#spanfmdate").show();
    //    i++;
    //    //return;
    //   }
    if (this.state.user_id != "0") {
   
      if (this.state.date == "" && this.state.formData.date == "") {
        $("#spanfmdatebox").addClass("is-invalid1");
        $("#spanfmdatelabel").css("color", "#dc3545");
        $("#spanfmdatebox")
          .children(".css-yk16xz-control")
          .css("border-color", "#dc3545");
        $("#spanfmdate").show();
        //  $("#complaint_date").css("display", "block");
        // return;
        i++;
      }
    } else {
      if (this.state.date == "") {
        $("#spanfmdatebox").addClass("is-invalid1");
        $("#spanfmdatelabel").css("color", "#dc3545");
        $("#spanfmdatebox")
          .children(".css-yk16xz-control")
          .css("border-color", "#dc3545");
        $("#spanfmdate").show();
        // return;
        i++;
      }

      // if (this.state.in_time == undefined) {
      //   // $('input[name="sunday_out_time"]').css("border-color", "blue");
      //   $('.in_time').children(".react-time-picker__wrapper").css("border-color", "#dc3545");
      //   $("#in_time").show();
      //   // k++;
      //   i++;
      // }

      // if (this.state.out_time == undefined) {
      //   // $('input[name="sunday_out_time"]').css("border-color", "blue");
      //   $('.out_time').children(".react-time-picker__wrapper").css("border-color", "#dc3545");
      //   $("#out_time").show();
      //   // k++;
      //   i++;
      // }
    
    }

    // 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 (this.state.user_id != "0") {
   
      if (this.state.date == "" && this.state.formData.date == "") {
        $("#spanfmdatebox").addClass("is-invalid1");
        $("#spanfmdatelabel").css("color", "#dc3545");
        $("#spanfmdatebox")
          .children(".css-yk16xz-control")
          .css("border-color", "#dc3545");
        $("#spanfmdate").show();
        //  $("#complaint_date").css("display", "block");
        // return;
        i++;
      }
    } else {
      if (this.state.date == "") {
        $("#spanfmdatebox").addClass("is-invalid1");
        $("#spanfmdatelabel").css("color", "#dc3545");
        $("#spanfmdatebox")
          .children(".css-yk16xz-control")
          .css("border-color", "#dc3545");
        $("#spanfmdate").show();
        // return;
        i++;
      }
    }
    
 
    if (i !== 0) {
      return;
    }
    this.setState({ submitted: true }, () => {
      var admin_id = localStorage.getItem("uname");
      //setTimeout(() => this.setState({ submitted: false }), 5000);
      fetch(
        myConstClass.BASE_URL +
          `shifts/add_shift_scheduler/` +
          admin_id +
          "/" +
          this.state.user_id,
        {
          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")),
                  "Shift Schedule Added Successfully..!",
                  this.options
                )
              : toastr.success(
                  TF("{0}", T("Success")),
                  "Shift Schedule Updated Successfully..!",
                  this.options
                );

            this.props.history.push(
              "/"  + "shiftschduler/listing"
            );
          } else {
            toastr.error(
              TF("{0}", T("Error")),
              "Can not Add Shift Schedule ..!",
              this.options
            );
          }
        })
        .catch();
    });
  };

  render() {
    const { formData, submitted, pay_codes, shifts, pay_code } = this.state;
    const { emp } = this.state;
    // 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>
    // }
    let payCodeOp = pay_codes
      ? pay_codes.map((cell) => {
          return { value: cell.id, label: cell.title };
          // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
        })
      : [];

    let shiftOp;
    shiftOp = shifts
      ? shifts.map((cell) => {
          return { value: cell.id, label: cell.shift_name };
        })
      : [];

    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={
                  "/" +
                 
                  "shiftschduler/listing"
                }
              >
                {" "}
                {T("Shift")} {T("Scheduler")} 
              </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>
                {T("Shift")} {T("Scheduler")}
                <span
                  style={{ color: "red", fontSize: "14px", float: "right" }}
                >
                  {" "}
                  {T("All fields marked with * are required")}{" "}
                </span>
              </h4>
              <hr />
              <Row>
                <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
                        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 disabled value="">
                          {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 value="">
                          {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>

                <Col lg={6}>
                  <Label id="spanfmdatelabel" for="example">
                    {T("Enter")} {T("Date")}
                  </Label>
                  <span style={{ color: "red", fontSize: "15px" }}> *</span>{" "}
                  <br />
                  {this.state.user_id != "0" ? (
                    <DatePicker
                      name="date"
                      required
                      minDate={moment().toDate()}
                      selected={this.state.date}
                      className="re_date_filter1 re_date_form is-untouched is-pristine av-valid"
                      onChange={this.handleFromDateChange}
                      readOnly
                      //placeholderText={'Select date'}
                      dateFormat="dd-MM-yyyy"
                      value={this.state.date || formData.date}
                      id="spanfmdatebox"
                    />
                  ) : (
                    <DatePicker
                      name="date"
                      //placeholderText={'Select date'}
                      required
                      minDate={moment().toDate()}
                      selected={this.state.date}
                      className="re_date_filter1 re_date_form is-untouched is-pristine av-valid"
                      onChange={this.handleFromDateChange}
                      dateFormat="dd-MM-yyyy"
                      value={this.state.date}
                      id="spanfmdatebox"
                    />
                  )}
                  <span
                    id="spanfmdate"
                    style={{ color: "red" }}
                    //style={this.state.showGalleryPlayButton}
                    style={{ display: "none" }}
                    class="invalid-feedback11"
                  >
                    {T("Enter")} {T("Date")}
                  </span>
                </Col>
              </Row>

              <br />

              <Row>
                {/* <Col lg={6} >
                     
                      <Label id="selectIDElabel1"> {TF("{0} {1} {2}", T("Select") , T("Employee"), T("Shift"))}</Label><span style={{color:'red',fontSize:'15px'}}> *</span>
                            <Select
                            value={employee_shift}
                            name="employee_shift"
                            placeholder='Select Employee Shift'
                            options={shiftOp}
                            onChange={this.handleShiftChange}
                            isClearable  
                            required
                            id="selectIDE1"
                          />
						 <span id="selectIDEs1" style={{color:"red"}}
					  //style={this.state.showGalleryPlayButton}
            style={{display:'none'}}
            class="invalid-feedback11"
					  
					  > {TF("{0} {1} {2}", T("Enter") , T("Employee"), T("Shift"))}
            </span>
                      
                  </Col> */}

                {/* 
<TimePicker onChange={this.onInTimeChange} 
//dateFormat={hh:mm}
format="hh:mm"
//dateFormat="hh:mm"
value={this.state.in_time} /> */}

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">
                      {TF(
                        "{0}-{1} - {2}:{3}",
                        T("In"),
                        T("Time"),
                        T("Hrs"),
                        T("Min")
                      )}

                      <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    </Label>
                    <AvInput
                      name="in_time"
                      id="example"
                      type="text"
                      required
                      value={formData ? formData.in_time : ""}
                    />
                    <AvFeedback>
                      {" "}
                      {TF("{0} {1} {2}!", T("Enter"), T("In"), T("Time"))}
                    </AvFeedback>
                  </AvGroup>
                </Col>

                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">
                      {TF(
                        "{0}-{1} - {2}:{3}",
                        T("Out"),
                        T("Time"),
                        T("Hrs"),
                        T("Min")
                      )}

                      <span style={{ color: "red", fontSize: "15px" }}> *</span>
                    </Label>
                    <AvInput
                      name="out_time"
                      id="example"
                      type="text"
                      required
                      value={formData ? formData.out_time : ""}
                    />
                    <AvFeedback>
                      {" "}
                      {TF("{0} {1} {2}!", T("Enter"), T("Out"), T("Time"))}
                    </AvFeedback>
                  </AvGroup>
                </Col>
              </Row>

              {/* <Row>
              <Col lg={6} >
                     
                     <Label > {TF("{0} {1} {2}", T("Employee") , T("Shift"), T("Time"))}</Label><br/>
                            <span id=""> {this.state.shifttime}</span>
            
                     
                 </Col>
			  
                 </Row> */}

              <br />
              <br />
             

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

              <FormGroup>
                <Link
                   to={
                    "/" +
                   
                    "shiftschduler/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;
