import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from "../../constant.js";
import "react-datepicker/dist/react-datepicker.css";
import filterFactory from "react-bootstrap-table2-filter";
import "./datepicker.scss";
import Select from "react-select";
import cookie from "react-cookies";
// import CsvDownloader from 'react-csv-downloader';
import swal from "sweetalert";
import moment from "moment";
import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Label,
  Card,
  CardBody,
  CardHeader,
  Container,
} 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 css
import { AvForm, AvGroup } from "availity-reactstrap-validation";
import { T, Config, TF } from "react-translator-component";
Config.default = localStorage.getItem("lang");

const { SearchBar } = Search;
const tableColumns = [
  // {
  //   dataField: "organization_id",
  //   text: TF("{0}", T("Organization")),
  //   sort: true,
  //   headerStyle: { width: "10%" },
  //   // filter: textFilter()
  //   sort: true,
  // },
  {
    dataField: "shift_name",
    text: TF("{0} {1}", T("Shift"), T("Name")),
    sort: true,
    headerStyle: { width: "10%" },
    // filter: textFilter()
    sort: true,
  },
  {
    dataField: "shift_code",
    text: TF("{0} {1}", T("Shift"), T("Code")),
    sort: true,
    headerStyle: { width: "10%" },
    // filter: textFilter()
    sort: true,
  },

  {
    dataField: "action",
    text: TF("{0}", T("Action")),
    headerStyle: { width: "10%" },
    csvExport: false,
  },
];

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

class Shifts extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    this.state = {
      user_id: 0,
      formData: [],
      formDataCSV: "",
      org: "",
      posts: "",
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
      languageCodes: [],
      language: cookie.load("language") ? cookie.load("language") : "en",
      question: cookie.load("question")
        ? cookie.load("question")
        : "What language do you prefer to read with?",
    };
    this.flag = 0;
    this.cid = 0;
    this.oid = 0;

    //   submitted: false,

    //for export
  }

  edit(e) {
    var empleave_add = localStorage.getItem("empshift_add");
    var empleave_edit = localStorage.getItem("empshift_edit");
    var login_type = localStorage.getItem("login_type");
    var edit_msg = localStorage.getItem("edit_msg");
    var add_msg = localStorage.getItem("add_msg");

    //  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")), add_msg);
          return;
        }
      }

      if (e != "0") {
        if (empleave_edit == "false") {
          toastr.error(TF("{0}", T("Error")), edit_msg);
          return;
        }
      }
    }
    this.props.history.push({
      pathname: "/" + "shifts/add",
      state: {
        _id: e,
      },
    });
  }
  change = (selectedOrg) => {
    this.setState({ selectedOrg });
    var admin_id = localStorage.getItem("uname");

    // this.oid = event.target.value;
    if (selectedOrg == null || selectedOrg == undefined) {
      this.oid = 0;
    } else {
      let x = Object.values(selectedOrg);
      // this.dep_id = event.target.value;
      this.oid = x[0];
    }
    fetch(
      myConstClass.BASE_URL + "shifts/getshifts/" + admin_id + "/" + this.oid
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.action = (
            <div>
              <Icon.Edit3
                style={{ margin: "0px 15px 0px 0px", cursor: "Pointer" }}
                onClick={() => this.edit(id)}
              />
              {/* <Icon.Trash2
                style={{ cursor: "Pointer" }}
                onClick={() => this.remove(id)}
              /> */}
            </div>
          );
          // console.log(element);
          element.id = i;
          i++;
        });
        this.setState({ formData: response });
      })
      .catch((err) => console.log(err));
  };
  remove(e) {
    var admin_id = localStorage.getItem("uname");
    var login_type = localStorage.getItem("login_type");
    var empleave_delete = localStorage.getItem("empshift_delete");
    var delete_msg = localStorage.getItem("delete_msg");
    if (login_type == "sub_admin") {
      var org_id = localStorage.getItem("organization_sub_admin");
      var dept_id = localStorage.getItem("department_sub_admin");
    } else {
      var org_id = 0;
      var dept_id = 0;
    }
    if (login_type == "sub_admin") {
      if (empleave_delete == "false") {
        toastr.error(TF("{0}", T("Error")), delete_msg);
        return;
      }
    }
    swal({
      title: TF("{0}", T("Are you sure?")),
      text: TF("{0}", T("Are you sure that you want to delete this record?")),
      icon: "warning",
      // buttons: true,
      buttons: {
        confirm: {
          text: TF("{0}", T("OK")),
          value: true,
          visible: true,
          className: "",
          closeModal: true,
        },
        cancel: {
          text: TF("{0}", T("Cancel")),
          value: false,
          visible: true,
          className: "Custom_Cancel",
          closeModal: true,
        },
      },
      dangerMode: true,
    }).then((result) => {
      if (result) {
        const options = {
          timeOut: parseInt(this.state.timeOut),
          showCloseButton: this.state.showCloseButton,
          progressBar: this.state.progressBar,
          position: this.state.position,
        };
        this.flag = 1;
        fetch(myConstClass.BASE_URL + `/shifts/deleteShift/` + admin_id, {
          method: "POST",
          body: e,
        })
          .then((response) => response.json())
          .then((response) => {
            //  alert(response)

            // this.setState({formData: []});
            toastr.success(
              TF("{0}", T("Success")),
              TF("{0} {1}..!", T("Shift"), T("Deleted Successfully")),
              options
            );
            // this.setState({formData: []}),
            fetch(
              myConstClass.BASE_URL +
                "shifts/getShifts/" +
                admin_id +
                "/" +
                this.oid +
                "/" +
                org_id +
                "/" +
                dept_id
            )
              .then((response) => response.json())
              .then((response) => {
                let i = 1;
                response.forEach((element) => {
                  let id = element.id;
                  element.action = (
                    <div>
                      <Icon.Edit3
                        style={{
                          margin: "0px 15px 0px 0px",
                          cursor: "Pointer",
                        }}
                        onClick={() => this.edit(id)}
                      />
                      {/* <Icon.Trash2
                        style={{ cursor: "Pointer" }}
                        onClick={() => this.remove(id)}
                      /> */}
                    </div>
                  );
                  // console.log(element);
                  element.id = i;
                  i++;
                });
                this.setState({ formData: response });
              })
              .catch((err) => console.log(err));
          })
          .catch();
      }
    });
  }

  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");
    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");
    } else {
      var org_id = 0;
      var dept_id = 0;
    }

    fetch(
      myConstClass.BASE_URL +
        "shifts/getShifts/" +
        admin_id +
        "/" +
        this.oid +
        "/" +
        org_id +
        "/" +
        dept_id
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.action = (
            <div>
              <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));

    fetch(
      myConstClass.BASE_URL + "organization/get_all_organizations/" + admin_id
    )
      .then((response) => response.json())
      .then((response) => {
        response.forEach((element) => {
          this.setState({ organization_id: [{ value: element.id, label: element.title }] });
        });
        this.setState({ org: response });
      })
      .catch((err) => console.log(err));
  }

  render() {
    var admin_id = localStorage.getItem("uname");
    const { org } = this.state;
    let orgOp = org
      ? org.map((cell) => {
          return { value: cell.id, label: cell.title };
        })
      : [];
    //for export

    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
            {" "}
            {T("All")} {T("Shift")}
          </HeaderTitle>

          <Breadcrumb>
            <BreadcrumbItem>
              <Link to={"/" + "dashboard"}>{T("Dashboard")}</Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {" "}
              {T("All")} {T("Shift")}
            </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:
                TF("{0} {1}_", T("Shift"), T("List")) + moment() + ".csv",
              exportAll: true,
            }}
            search
          >
            {(props) => (
              <div>
                <CardHeader></CardHeader>
                <CardBody>
                  <AvForm id="sform">
                    {/* <Row className="f_class_present">
                <div class="col-md-3"></div>
                  <div class="col-md-3"></div>
                  <div class="col-md-1"></div>
                    <div class="col-md-4">
                      <AvGroup>
                        <Label for="example" className="search_title">Search{TF("{0}", T("Error"))}</Label>
                        <AvInput name="search" className="search_present" onChange={this.search} type="text" id="example"/>
                      </AvGroup>
                    </div> <br/>
                  </Row> */}
                    <Row>
                      <div class="col-md-4">
                        <AvGroup>
                          <label>
                            {TF("{0} {1}", T("Select"), T("Organization"))}
                          </label>
                          <Select
                            value={this.state.organization_id}
                            name="organization_id"
                            onChange={this.change}
                            options={orgOp}
                            isClearable
                            placeholder={TF(
                              "{0} {1}",
                              T("Select"),
                              T("Organization")
                            )}
                          />
                        </AvGroup>
                      </div>

                      <div class="col-md-5"></div>
                    </Row>

                    <Row>
                      <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-4" style={{ marginTop: "29px" }}>
                        <Label for="example"></Label>
                        <SearchBar
                          {...props.searchProps}
                          placeholder={T("Search")}
                        />
                      </div>
                    </Row>
                  </AvForm>
                  <br />
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                    <Row className="shift"></Row>

                    {/* <Row>
              <div class="col-md-3">
                 <AvGroup>
                 <AvField
                  type="select"
                  name="organization_id"
                  label="Select Organization"
                  onChange={this.ochange}  
                  value={this.state.organization_id}
                >
                  <option value={0}>All Organization</option>
                  {org ?  org.map((cell, i) => {
                  return(<option value={cell.id}>{cell.title}</option>)
                  }) : ''}       
                </AvField> 
                </AvGroup>
               </div> 
           </Row><br/> */}
                    {/* <Row>
           <div class="col-md-4"> */}
                    {/* <Label for="example" className="search_title">{TF("{0}", T("Error"))}</Label>
    
           <MyExportCSV {...props.csvProps} /> */}
                    {/* <div class="col-md-4">
           <CSVLink filename={"Attendance_"+moment()+".csv"}
          className="btn btn-secondary" data={this.state.formDataCSV} headers={headers}>Export</CSVLink>
        </div> */}
                    {/* </div>
             <div class="col-md-4"></div>
            </Row> */}
                  </AvForm>
                  <BootstrapTable
                    {...props.baseProps}
                    bootstrap4
                    keyField="id"
                    bordered={false}
                    filter={filterFactory()}
                    filterPosition="top"
                    pagination={paginationFactory({
                      // sizePerPage: 25,
                      sizePerPage: 10,
                      sizePerPageList: [5, 10, 25, 50],
                    })}
                  />
                </CardBody>
              </div>
            )}
          </ToolkitProvider>
        </Card>
      </Container>
    );
  }
}

export default Shifts;
