import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from "../../constant.js";
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 "./common.scss";
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 cs
import swal from "sweetalert";
import { AvForm } from "availity-reactstrap-validation";
import { T, Config, TF } from "react-translator-component";
Config.default = localStorage.getItem("lang");
const { SearchBar } = Search;
const tableColumns = [
  {
    dataField: "type",
    text: T("Category"),
    sort: true,
    headerStyle: { width: "30%" },
  },
  {
    dataField: "description",
    text: T("Description"),
    sort: true,
    headerStyle: { width: "60%" },
  },
  {
    dataField: "action",
    text: 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 Announcements extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    this.state = {
      user_id: 0,
      formData: [],
      emp: "",
      posts: "",
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
      nooteinfo: "",
      visiblepoints: false,
    };
    this.oid = 0;
  }

  /*edit(e) { 
        this.props.history.push('/'+myConstClass.TENANT_PAGE_PATH+'admin/add/'+e);
      }*/

  edit(e) {
    var empleave_add = localStorage.getItem("compcat_add");
    var empleave_edit = localStorage.getItem("compcat_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: "/"  + "settingsticketcategory/add",
      strict: false,
      sensitive: false,
      state: {
        _id: e,
      },
    });
  }

  remove(e) {
    var admin_id = localStorage.getItem("uname");

    if (this.pos_id == null || this.pos_id == "") {
      this.pos_id = 0;
    } else {
      this.pos_id = this.pos_id;
    }
    if (this.dep_id == null || this.dep_id == "") {
      this.dep_id = 0;
    } else {
      this.dep_id = this.dep_id;
    }

    swal({
      title: "Are you sure?",
      text: "Are you sure that you want to delete this record?",
      icon: "warning",
      // buttons: true,
      buttons: {
        confirm: {
          text: "OK",
          value: true,
          visible: true,
          className: "",
          closeModal: true,
        },
        cancel: {
          text: "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 + `/user/deleteCategory/` + admin_id, {
          method: "POST",
          body: e,
        })
          .then(
            toastr.success(
              "Success",
              "Record Deleted Successfully..!",
              options
            ),

            // fetch(
            //   myConstClass.BASE_URL +
            //     "/user/getUsers/" +
            //     admin_id +
            //     "/" +
            //     this.cid +
            //     "/" +
            //     this.sid +
            //     "/" +
            //     this.pos_id +
            //     "/" +
            //     this.dep_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))


            this.componentDidMount()
          )
          .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");
    var login_id = localStorage.getItem("login_id");
    if (admin_id == null) {
      this.routeChange();
    }
    fetch(myConstClass.BASE_URL + "user/getTicketCategory/" + admin_id)
      //fetch(myConstClass.BASE_URL+url)
      .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));
  }

  render() {
    var admin_id = localStorage.getItem("uname");
    var login_type = localStorage.getItem("login_type");

    return (
      <Container fluid>
        <Header>
          <HeaderTitle>
          {T("Ticket")} {T("Category")} 
          </HeaderTitle>

          <Breadcrumb>
            {admin_id != "0" && login_type != "emp" ? (
              <BreadcrumbItem>
                <Link to={"/"  + "dashboard"}>
                  {T("Dashboard")}
                </Link>
              </BreadcrumbItem>
            ) : (
              ""
            )}
            {/* <BreadcrumbItem>
              <Link to="/dashboard">measures</Link>
            </BreadcrumbItem> */}
            {admin_id != "0" && login_type != "emp" ? (
              <BreadcrumbItem active>
                {T("Ticket")} {T("Category")} 
              </BreadcrumbItem>
            ) : (
              ""
            )}
            {/* <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> */}
            {admin_id != "0" && login_type != "emp" ? (
              <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>
          {/* <span >{T("ADD")}</span> */}
        </Header>
        <Card>
          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV={{
              fileName:
                TF("{0} {1} {2}_", T("Ticket"), T("Category"), T("List")) +
                moment() +
                ".csv",
              exportAll: true,
            }}
            search
          >
            {(props) => (
              <div>
                <CardHeader></CardHeader>
                <CardBody>
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                    <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-4"></div>
                      <div class="col-md-1"></div>
                      <div class="col-md-3" style={{ marginTop: "29px" }}>
                        <Label for="example"> </Label>
                        <SearchBar
                          {...props.searchProps}
                          placeholder={T("Search")}
                        />
                      </div>
                    </Row>
                  </AvForm>
                  <br />
                  <BootstrapTable
                    {...props.baseProps}
                    bootstrap4
                    bordered={false}
                    pagination={paginationFactory({
                      // sizePerPage: 25,
                      sizePerPage: 10,
                      sizePerPageList: [5, 10, 25, 50],
                    })}
                  />
                </CardBody>
              </div>
            )}
          </ToolkitProvider>
        </Card>

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

export default Announcements;
