import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from "../../constant.js";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./datepicker.scss";
//import moment from 'moment';
import {
  Breadcrumb,
  BreadcrumbItem,
  Button,
  Row,
  Col,
  Label,
  Input,
  Card,
  CardBody,
  CardHeader,
  Container,
  Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
} from "reactstrap";

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

import BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider, { Search } from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import "react-confirm-alert/src/react-confirm-alert.css";
import { AvForm, AvField, AvGroup } from "availity-reactstrap-validation";

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

function imageFormatter(cell, row) {
  // alert(row.image);
  if (row.is_view == "0") {
    return { backgroundColor: "#f8f9fa" };
  }
}

const tableColumns = [
  {
    dataField: "ticket_no",
    text: TF("{0} {1}", T("Ticket"), T("No")),
    sort: true,
    headerStyle: { width: "20%" },
    style: imageFormatter,
  },
  {
    dataField: "employee_id",
    text: T("Employee"),
    sort: true,
    headerStyle: { width: "25%" },
    style: imageFormatter,
  },
  {
    dataField: "created_at",
    text: TF("{0}", T("Date")),
    sort: true,
    headerStyle: { width: "20%" },
    style: imageFormatter,
  },
  {
    dataField: "ticketcategory",
    text: TF("{0} {1}", T("Ticket"), T("Category")),
    sort: true,
    headerStyle: { width: "20%" },
    style: imageFormatter,
  },
  {
    dataField: "status",
    text: TF("{0}", T("Status")),
    sort: true,
    headerStyle: { width: "15%" },
    style: imageFormatter,
  },
  // {
  //   dataField: "to_time",
  //   text: TF("{0} {1}", T("To"), T("Time")),
  //   sort: true,
  //   headerStyle: { width: "10%" },
  //   style: imageFormatter,
  // },
  // {
  //   dataField: "total_ot",
  //   text: TF("{0} {1}", T("Total"), T("Overtime")),
  //   sort: true,
  //   headerStyle: { width: "8%" },
  //   style: imageFormatter,
  // },
  // {
  //   dataField: "actual_days",
  //   text: TF("{0} {1}", T("Actual"), T("Days")),
  //   sort: true,
  //   headerStyle: { width: "10%" },
  //   style: imageFormatter
  // },
  // {
  //   dataField: "reason",
  //   text: TF("{0}", T("Reason")),
  //   sort: true,
  //   headerStyle: { width: "10%" },
  //   style: imageFormatter
  // },
  // {
  //   dataField: "status",
  //   text: TF("{0}", T("Status")),
  //   sort: true,
  //   headerStyle: { width: "8%" },
  //   style: imageFormatter
  // },
  {
    dataField: "action",
    text: TF("{0}", T("Action")),
    headerStyle: { width: "14%" },
    csvExport: false,
    // formatter: imageFormatter8
  },
];

const MyExportCSV = (props) => {
  const handleClick = () => {
    props.onExport();
  };
  return (
    <div>
      <button className="btn btn-secondary mt-2" onClick={handleClick}>
        {TF("{0}", T("Export"))}
      </button>
    </div>
  );
};

class Leaves extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    this.state = {
      user_id: 0,
      // from_date:Date.now(),
      // to_date:Date.now(),

      // from_date: new Date(new Date().getFullYear(), new Date().getMonth(), 1),
      // to_date: new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0),
      formData: [],
      emp: "",
      posts: "",
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
    };
    this.sid = 1;
    // this.flag = 0; this.cid = 0; this.oid = 0; this.lid = 0; this.sid = 0;
    // this.change = this.change.bind(this);
    // this.ochange = this.ochange.bind(this);
    // this.ochangeLeave = this.ochangeLeave.bind(this);
    // this.handleChange = this.handleChange.bind(this);

    //   submitted: false,
  }

  /*edit(e) { 
      this.props.history.push('/'+myConstClass.TENANT_PAGE_PATH+'leaves/add/'+e);
    }*/
  edit(e) {
    var empleave_add = localStorage.getItem("empleave_add");
    var empleave_edit = localStorage.getItem("empleave_edit");
    var login_type = localStorage.getItem("login_type");

    //  alert(empleave_add);  alert(login_type); alert(e);

    if (login_type == "sub_admin") {
      if (e == "0") {
        if (empleave_add == "false") {
          // alert('hii')
          toastr.error(
            TF("{0}", T("Error")),
            TF("{0}...!", T("Can not Add Privilege"))
          );
          return;
        }
      }

      if (e != "0") {
        if (empleave_edit == "false") {
          toastr.error(
            TF("{0}", T("Error")),
            TF("{0}...!", T("Can not Edit Privilege"))
          );
          return;
        }
      }
    }
    this.props.history.push({
      pathname: "/" + "employeesissues/add",
      state: {
        _id: e,
      },
    });
  }

  routeChange() {
    this.props.history.push("/");
  }

  componentDidMount() {
    document.querySelector(".react-bootstrap-table").style.minHeight = "243px";
    var admin_id = localStorage.getItem("uname");
    var login_type = localStorage.getItem("login_type");
    var sub_admin_role = localStorage.getItem("sub_admin_role");
    if (admin_id == null) {
      this.routeChange();
    }

    if (login_type == "sub_admin") {
      var org_id = localStorage.getItem("organization_sub_admin");
      var dept_id = localStorage.getItem("department_sub_admin");
      // url='organization/getIncidents/'+admin_id+'/'+this.sid+'/'+this.oid +'/'+org_id+'/'+dept_id;
    } else {
      var org_id = 0;
      var dept_id = 0;
      // url='organization/getIncidents/'+admin_id+'/'+this.sid+'/'+this.oid +'/'+org_id+'/'+dept_id;
    }

    // if (login_type != 'emp') {
    fetch(myConstClass.BASE_URL + "attendance/getEmployeeIssues/0/" + this.sid+'/'+admin_id)
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          // if(element.status=="Approved" || element.status=="Rejected")
          // {
          //   element.action = <div><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;

          // }
          //      else{
          element.action = (
            <div>
              {/* <Icon.Eye style={{ margin: '0px 15px 0px 0px', cursor: 'Pointer' }} onClick={() => this.view1(id)} /> */}
              <Icon.Edit3
                style={{ margin: "0px 15px 0px 0px", cursor: "Pointer" }}
                onClick={() => this.edit(id)}
              />
              {/* <Icon.Trash2 style={{ cursor: 'Pointer' }} onClick={() => this.remove(id)} /> */}
            </div>
          );
          //  }

          element.id = i;
          i++;
        });
        this.setState({ formData: response });
      })
      .catch((err) => console.log(err));
    // }

    // else if (login_type == 'emp' && departementhead != '0') {
    //   fetch(myConstClass.BASE_URL + 'attendance/getEmployeeOvertimeRequest/' + admin_id + '/' + this.cid + '/' + fdate + '/' + tdate + '/' + this.oid + '/' + login_id + '/' + departementhead + '/' + org_id + '/' + dept_id)
    //     .then(response => response.json())
    //     .then(response => {
    //       let i = 1;
    //       response.forEach(element => {
    //         let id = element.leave_id;
    //         //     element.action = <div><Icon.Edit3 style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.edit(id)} />
    //         // </div>;

    //         if (element.status == T("Approved") || element.status == T("Rejected")) {
    //           element.action = <div>{element.status}</div>;

    //         }
    //         else {
    //           element.action = <div><Icon.Edit3 style={{ margin: '0px 15px 0px 0px', cursor: 'Pointer' }} onClick={() => this.edit(id)} /></div>;
    //         }

    //         element.leave_id = i;
    //         i++;
    //       });
    //       this.setState({ formData: response })
    //     }).catch(err => console.log(err))
    // }

    // else {
    //   fetch(myConstClass.BASE_URL + 'attendance/getEmployeeOvertimeRequest/' + admin_id + '/' + this.cid + '/' + fdate + '/' + tdate + '/' + this.oid + '/' + login_id + '/' + this.lid + '/' + this.sid + '/' + org_id + '/' + dept_id)
    //     .then(response => response.json())
    //     .then(response => {
    //       let i = 1;
    //       response.forEach(element => {
    //         let id = element.leave_id;
    //         if (element.status == T("Approved") || element.status == T("Rejected")) {
    //           element.action = <div>{element.status}</div>;

    //         }
    //         else {
    //           element.action = <div><Icon.Edit3 style={{ margin: '0px 15px 0px 0px', cursor: 'Pointer' }} onClick={() => this.edit(id)} /></div>;
    //         }
    //         //  element.action = <div></div>;
    //         element.leave_id = i;
    //         i++;
    //       });
    //       this.setState({ formData: response })
    //     }).catch(err => console.log(err))
    // }

    // fetch(myConstClass.BASE_URL+'user/get_all_Employees/'+admin_id+'/'+this.oid)
    // .then(response => response.json())
    // .then(response =>{this.setState({emp: response})}).catch(err => console.log(err))
  }
  status_change = (event) => {
    this.setState({ status: event });
    this.sid = event.target.value;

    this.setState({ formData: [] });

    var admin_id = localStorage.getItem("uname");
    // this.sid = event.target.value;
    fetch(myConstClass.BASE_URL + "attendance/getEmployeeIssues/0/" + this.sid+'/'+admin_id)
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          // if(element.status=="Approved" || element.status=="Rejected")
          // {
          //   element.action = <div><Icon.Trash2 style={{cursor:'Pointer'}} onClick={() =>this.remove(id)}/></div>;

          element.action = (
            <div>
              {/* <Icon.Eye style={{ margin: '0px 15px 0px 0px', cursor: 'Pointer' }} onClick={() => this.view1(id)} /> */}
              <Icon.Edit3
                style={{ margin: "0px 15px 0px 0px", cursor: "Pointer" }}
                onClick={() => this.edit(id)}
              />
              {/* <Icon.Trash2 style={{ cursor: 'Pointer' }} onClick={() => this.remove(id)} /> */}
            </div>
          );
        });
        this.setState({ formData: response });
      })
      .catch((err) => console.log(err));
  };
  render() {
    var admin_id = localStorage.getItem("uname");
    var login_type = localStorage.getItem("login_type");
    var departementhead = localStorage.getItem("departementhead");
    const { emp } = this.state;
    const { org, formDataC } = this.state;
    //alert(login_type);

    let fileName =
      TF(
        "{0} {1} {2} _",
        T("Employees"),
       
        T("Request"),
        T("List")
      ) + ".csv";

    let import_btn;
    if (login_type == "hr_admin") {
      import_btn = (
        <div>
          <Col lg={6}>
            {/* <Link to={'/'  + "shiftsleaves/dlisting"}> <Button color="primary" type="button" >{T("Archived")}</Button></Link> */}
          </Col>
        </div>
      );
    } else {
      import_btn = (
        <div>
          <Col lg={6}>
            {/* <Link to={'/'+myConstClass.TENANT_PAGE_PATH+"employee_bulk_import/import"}> <Button color="primary" type="button" className="import_btn">Import +</Button></Link> */}
          </Col>
        </div>
      );
    }
    // var admin_id= localStorage.getItem('uname');
    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
            {" "}
          Employee Request
          </HeaderTitle>
          
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to={"/" + "dashboard"}>{T("Dashboard")}</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>
                Employee Request
              </BreadcrumbItem>
              {(admin_id !='0' ) ?
              <button
                class="mr-1 mb-1 btn btn-outline-secondary"
                onClick={() => this.edit(this.state.user_id)}
                style={{
                  color: "#ffffff",
                  border: "1px solid #ffffff",
                  float: "right !important",
                  margin: "auto",
                }}
              > 
               
                <Icon.PlusCircle />
                &nbsp;&nbsp;{T("ADD")}
                </button>
                  : '' }
            </Breadcrumb>
         
        </Header>
        <Card>
          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV={{
              fileName: fileName,
              exportAll: true,
            }}
            search
          >
            {(props) => (
              <div>
                <CardHeader></CardHeader>
                <CardBody>
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                    <Row>
                      <div class="col-md-4">
                        <AvGroup>
                          <AvField
                            type="select"
                            name="organization_id"
                            label={TF("{0} {1}", T("Select"), T("Status"))}
                            onChange={this.status_change}
                            value={this.sid}
                          >
                            <option value={1}>{TF("{0}", T("Pending"))}</option>
                            <option value={2}>
                              {TF("{0}", T("In Progress"))}
                            </option>
                            <option value={3}>
                              {TF("{0}", T("Resolved"))}
                            </option>
                          </AvField>
                        </AvGroup>
                      </div>
                    </Row>

                    <Row>
                      {login_type != "emp" ? (
                        <div class="col-md-4">
                          <Label for="example" className="search_title"></Label>
                          <MyExportCSV {...props.csvProps} />
                        </div>
                      ) : (
                        <div class="col-md-4"></div>
                      )}

                      <div class="col-md-3"></div>
                      <div class="col-md-2" style={{ marginTop: "29px" }}>
                        {" "}
                        {import_btn}
                      </div>
                      <div class="col-md-3" style={{ marginTop: "29px" }}>
                        <Label for="example"> </Label>
                        <SearchBar {...props.searchProps} />
                      </div>
                    </Row>
                  </AvForm>
                  <br />
                  <BootstrapTable
                    {...props.baseProps}
                    bootstrap4
                    bordered={false}
                    pagination={paginationFactory({
                      // sizePerPage: 25,
                      sizePerPage: 10,
                      sizePerPageList: [5, 10, 25, 50],
                    })}
                  />
                </CardBody>
              </div>
            )}
          </ToolkitProvider>

          <Modal
            size="lg"
            style={{ maxWidth: "700px", width: "100%" }}
            isOpen={this.state.visiblepoints1}
            //onOk={this.handleOk}
            // onCancel={this.handleCancel}
          >
            <ModalHeader></ModalHeader>
            <ModalBody className="text-center m-9">
              <CardHeader>{TF("{0} {1}", T("View"), T("Leave"))}</CardHeader>
              <CardBody>
                <Row>
                  {/* <Col lg={6}>
                
                  <AvField
                  type="select"
                  name="complaint_from"
                  label="Complaint From"
                  value={formData ? formData.complaint_from:''}
				  
				  // onChange={this.dep_change}
                >
				<option hidden value="">Select Employee</option>
                  {empinfo ?  empinfo.map((cell, i) => {
                  return(
				  
				   
				  <option value={cell.id}>{cell.first_name}  {cell.last_name}</option>)
                  }) : ''}       
                </AvField>
                

                </Col> */}

                  <Col lg={6}>
                    <Label for="example"> {T("Name")}</Label>
                    <Input
                      name="name"
                      id="example"
                      value={
                        formDataC
                          ? formDataC.first_name + " " + formDataC.last_name
                          : ""
                      }
                      disabled
                    />
                    {/* <AvInput name="subject" id="example"  value={formDataC ? formDataC.subject:''}/> */}
                    {/* <label>{formDataC.subject}</label> */}
                  </Col>

                  <Col lg={6}>
                    <Label for="example">
                      {TF("{0} {1} !", T("From"), T("Date"))}
                    </Label>
                    <Input
                      name="from_date"
                      id="example"
                      value={formDataC ? formDataC.from_date : ""}
                      disabled
                    />
                    {/* <AvInput name="subject" id="example"  value={formDataC ? formDataC.subject:''}/> */}
                    {/* <label>{formDataC.subject}</label> */}
                  </Col>

                  <Col lg={6}>
                    <Label for="example">
                      {TF("{0} {1} !", T("To"), T("Date"))}
                    </Label>
                    <Input
                      name="to_date"
                      id="example"
                      value={formDataC ? formDataC.to_date : ""}
                      disabled
                    />
                    {/* <AvInput name="subject" id="example"  value={formDataC ? formDataC.subject:''}/> */}
                    {/* <label>{formDataC.subject}</label> */}
                  </Col>

                  <Col lg={6}>
                    <Label for="example">{TF("{0}", T("Reason"))}</Label>
                    <Input
                      name="reason"
                      id="example"
                      value={formDataC ? formDataC.reason : ""}
                      disabled
                    />
                    {/* <AvInput name="subject" id="example"  value={formDataC ? formDataC.subject:''}/> */}
                    {/* <label>{formDataC.subject}</label> */}
                  </Col>
                  {/* <Col lg={6}>   */}

                  {/* <Label for="example">Description</Label>
                  <Input name="subject" id="example"  value={formDataC ? formDataC.description:''} disabled/>
                  
               
             
             </Col> */}
                  {/* <Col lg={6}>
              
                <Label for="example">Action Taken</Label>
<br/>                <textarea   style={{width: '307px'}} name="subject" id="example" value={formDataC.action_taken} disabled></textarea>
               
               
           
              </Col>  */}
                </Row>
                <Row>
                  {/* <Col lg={6}>
                  <label>Status</label>
                     <AvField
                          type="select"
                          id="status"             
                          value={formData ? formData.status:''}
                          onChange={this.status}
                          name='status'
                          className="mb-3"
                      >
                      <option value="1">Open</option>
                      <option value="2">Close</option>
                      
                   </AvField>
                </Col>
				 */}

                  <Col lg={6}>{/* {c_file} */}</Col>
                </Row>
              </CardBody>
            </ModalBody>
            <br />
            <ModalFooter>
              <Button
                color="secondary"
                onClick={() => this.toggleEditLeaveTemplate1()}
              >
                {TF("{0}", T("Close"))}
              </Button>{" "}
            </ModalFooter>
          </Modal>
        </Card>

        {/* <ExportCSVTable /> */}
      </Container>
    );
  }
}

export default Leaves;
