import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import "react-datepicker/dist/react-datepicker.css";
import "./bulk_import.scss";

import {
  Breadcrumb,
  BreadcrumbItem,
  Row,
  Col,
  Card,
  CardBody,
  Container,
  Button,
  Label,
  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 from "react-bootstrap-table2-toolkit";
import paginationFactory from "react-bootstrap-table2-paginator";
import * as myConstClass from "../../constant.js";
import { toastr } from "react-redux-toastr";

import { AvForm } from "availity-reactstrap-validation";
import { T, Config, TF } from "react-translator-component";
Config.default = localStorage.getItem("lang");
// const file_link = `${process.env.PUBLIC_URL}/CsvFile/sample-csv-bulk_employee.csv`;
const file_link = `${process.env.PUBLIC_URL}/CsvFile/sample_shift_schedular.csv`;

const tableColumns = [
  {
    dataField: "no",
    text: "Row No.",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "employee_id",
    text: "Emp ID",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "date",
    text: "Date",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "in_time",
    text: "In Time",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "out_time",
    text: "Out Time",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "rest_time",
    text: "Rest Time",
    sort: true,
    headerStyle: { width: "15%" },
  },
  {
    dataField: "pay_code",
    text: "PayCode",
    sort: true,
    headerStyle: { width: "15%" },
  },
];

class Importschedular extends PureComponent {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.change = this.change.bind(this);

    this.state = {
      selectedFile: null,
      posts: "",
      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,
    };
  }

  onChangeHandler = (event) => {
    console.log(event.target.files[0]);
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    });
  };

  change(event) {
    this.oid = event.target.value;
  }

  onSaveClickHandler = () => {
    const data = new FormData();
    data.append("file", this.state.selectedFile);
    data.append("session_id", localStorage.getItem("session_id"));
    fetch(myConstClass.BASE_URL + `/shifts/save_import_data/`, {
      method: "POST",
      body: data,
    })
      .then((response) => response.json())
      .then((response) => {
        if (response == true) {
          toastr.success(
            TF("{0}", T("Success")),
            TF("{0}", T(myConstClass.ADDMSG)),
            this.options
          );
          this.props.history.push(
            "/"  + "shift_schedular/listing"
          );
        } else if (response.err) {
          toastr.error(TF("{0}", T("Error")), response.err, this.options);
        } else {
          toastr.error(TF("{0}", T("Error")), "Import Failed..!", this.options);
        }
      })
      .catch();
  };

  onClickHandlerTemp = () => {
    const data = new FormData();
    //alert(answer_array['3']);
    var admin_id = localStorage.getItem("uname");
    //this.state.user_id =this.props.location.state._id;
    //data.append('file', this.state.selectedFile);
    data.append("session_id", localStorage.getItem("session_id"));
    data.append("admin_id", admin_id);
    //  data.append('pay_line_id',this.state.user_id);
    fetch(myConstClass.BASE_URL + `/shifts/importtempshift/`, {
      method: "POST",
      body: data,
    })
      .then((response) => response.json())
      .then((response) => {
        this.setState({ posts1: response });

        this.setState({ visiblepoints1: true });
      })
      .catch((err) => console.log(err));
  };

  onClickHandlerCopyDatabse = () => {
    this.setState({ visiblepoints1: false });
    const data = new FormData();

    var admin_id = localStorage.getItem("uname");
    //this.state.user_id =this.props.location.state._id;
    //data.append('file', this.state.selectedFile);
    data.append("session_id", localStorage.getItem("session_id"));
    data.append("admin_id", admin_id);
    fetch(myConstClass.BASE_URL + `/shifts/importtempshifttable/`, {
      method: "POST",
      body: data,
    })
      .then((response) => response.json())
      .then((response) => {
        if (response == true) {
          toastr.success(
            TF("{0}", T("Success")),
            TF("{0}", T(myConstClass.ADDMSG)),
            this.options
          );
          this.props.history.push(
            "/"  + "shift_schedular/listing"
          );
        } else if (response.err) {
          toastr.error(TF("{0}", T("Error")), response.err, this.options);
        } else {
          toastr.error(TF("{0}", T("Error")), "Copied Failed..!", this.options);
        }
      })
      .catch();
  };

  onClickHandler = () => {
    if (this.state.selectedFile == null) {
      toastr.error(
        TF("{0}", T("Error")),
        TF("{0}", T(myConstClass.ERRORMSG)),
        //this.options
      );
      return;
    }

    const data = new FormData();
    data.append("file", this.state.selectedFile);
    data.append("session_id", localStorage.getItem("session_id"));
    fetch(myConstClass.BASE_URL + `/shifts/import/`, {
      method: "POST",
      body: data,
    })
      .then((response) => response.json())
      .then((response) => {
        this.setState({ posts: response });

        this.setState({ visiblepoints: true });
      })
      .catch((err) => console.log(err));
  };

  toggleCloseLeaveTemplate = () => {
    this.setState({ visiblepoints: false });
  };

  toggleCloseLeaveTemplateTable = () => {
    this.setState({ visiblepoints1: false });
  };

  routeChange() {
    this.props.history.push("/");
  }
  handleSubmit = () => {
    //alert(JSON.stringify($('#pform').serializeArray()));
  };
  componentDidMount() {
    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
  }

  render() {
    return (
      <Container fluid>
        <Header>
          <HeaderTitle> {T("Work")} {T("Schedule")}  {T("Import")} {" "}</HeaderTitle>
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to={"/"  + "dashboard"}>
                {T("Dashboard")}
              </Link>
            </BreadcrumbItem>
            <BreadcrumbItem active>
              {T("Work")} {T("Schedule")}  {T("Import")} {" "}
            </BreadcrumbItem>
          </Breadcrumb>
        </Header>
        <Card>
          <CardBody>
            <h4>
              {T("Import")} {T("By")} {T("CSV")} {T("File")}
            </h4>
            <Row>
              <div class="col-md-6">
                <AvForm id="pform" onSubmit={this.handleSubmit}>
                  <Row>
                    <Col lg={6}>
                      <Label for="example">
                        {T("Select")} {T("File")}{" "}
                      </Label>{" "}
                      <br />
                      <input
                        type="file"
                        required
                        name="file"
                        onChange={this.onChangeHandler}
                      />
                    </Col>
                  </Row>
                  <br />
                  <Col md={6}>
                    <Row>
                      <button
                        type="button"
                        style={{ width: "40%", height: "10%" }}
                        className="btn btn-primary btn-block col-md-4"
                        onClick={this.onClickHandler}
                      >
                        {T("Upload")}
                      </button>
                    </Row>
                  </Col>
                  <br />

                  <Modal
                    size="lg"
                    style={{ maxWidth: "1251px", width: "100%" }}
                    isOpen={this.state.visiblepoints}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                  >
                    <ModalHeader>{T("Preview")}</ModalHeader>
                    <ModalBody className="text-center m-9">
                      {this.state.posts ? (
                        <div>
                          <ToolkitProvider
                            keyField="name"
                            data={this.state.posts}
                            columns={tableColumns}
                            exportCSV
                          >
                            {(props) => (
                              <div>
                                <BootstrapTable
                                  {...props.baseProps}
                                  bootstrap4
                                  bordered={false}
                                  pagination={paginationFactory({
                                    // sizePerPage: 25,
                                    sizePerPage: 10,
                                    sizePerPageList: [5, 10, 25, 50],
                                  })}
                                />
                              </div>
                            )}
                          </ToolkitProvider>
                        </div>
                      ) : (
                        ""
                      )}
                    </ModalBody>
                    <br />
                    <ModalFooter>
                      {/* <Col md={6}> */}
                      <Button
                        color="secondary"
                        onClick={() =>
                          this.toggleCloseLeaveTemplate(this.state.id)
                        }
                      >
                        {T("Close")}
                      </Button>{" "}
                      <Button type="button" onClick={this.onSaveClickHandler}>
                        {T("Save")}
                      </Button>
                      {/* </Col> */}
                    </ModalFooter>
                  </Modal>
                </AvForm>
              </div>

              <div class="col-md-6">
                <br />
                <Row>
                  <Col lg={6}>
                    <Label for="example">{T("Download Sample CSV File")}</Label>
                    <br />{" "}
                    <a href={file_link}>
                      <Button color="primary" type="button" className="">
                        {T("Download Sample CSV File")}
                      </Button>
                    </a>
                  </Col>
                </Row>
                <br />
                <hr />
              </div>
            </Row>

            <hr />
            {/* <h4>{T("Preview Of Shift Scheduler Table")}</h4> */}

            <Col md={6}>
              <Row>
                <Button
                  type="button"
                  style={{ width: "40%", height: "10%" }}
                  className="btn  btn-block col-md-4"
                  onClick={this.onClickHandlerTemp}
                >
                  {T("Work Scheduler Import of Table")}
                </Button>
              </Row>
            </Col>
            <hr />

            <Link
              to={
                "/"  + "shift_schedular/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>

            <Modal
              size="lg"
              style={{ maxWidth: "1251px", width: "100%" }}
              isOpen={this.state.visiblepoints1}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              <ModalHeader>{T("Preview")}</ModalHeader>
              <ModalBody className="text-center m-9">
                {this.state.posts1 ? (
                  <div>
                    <ToolkitProvider
                      keyField="name"
                      data={this.state.posts1}
                      columns={tableColumns}
                      exportCSV
                    >
                      {(props) => (
                        <div>
                          <BootstrapTable
                            {...props.baseProps}
                            bootstrap4
                            bordered={false}
                            pagination={paginationFactory({
                              // sizePerPage: 25,
                              sizePerPage: 10,
                              sizePerPageList: [5, 10, 25, 50],
                            })}
                          />
                        </div>
                      )}
                    </ToolkitProvider>
                  </div>
                ) : (
                  ""
                )}
              </ModalBody>
              <br />
              <ModalFooter>
                {/* <Col md={12}>
              <Row> */}
                <Button
                  color="secondary"
                  onClick={() =>
                    this.toggleCloseLeaveTemplateTable(this.state.id)
                  }
                >
                  {T("Close")}
                </Button>{" "}
                {this.state.posts1 ? (
                  <Button
                    type="button"
                    className="btn"
                    onClick={this.onClickHandlerCopyDatabse}
                  >
                    {T("Copy")}
                  </Button>
                ) : (
                  ""
                )}
                {/* </Row>
          </Col> */}
              </ModalFooter>
            </Modal>
          </CardBody>
        </Card>
      </Container>
    );
  }
}
export default Importschedular;
