import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from "../../constant.js";
import $ from "jquery";
import {
  Breadcrumb,
  BreadcrumbItem,
  Button,
  Row,
  Col,
  Label,
  Input,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";
import CsvDownloader from "react-csv-downloader";
import BootstrapTable from "react-bootstrap-table-next";
import ToolkitProvider 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 { confirmAlert } from "react-confirm-alert"; // Import
import "react-confirm-alert/src/react-confirm-alert.css"; // Import css
import { Redirect } from "react-router-dom";
import swal from "sweetalert";
import "./common.scss";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox,
} from "availity-reactstrap-validation";
const tableColumns = [
  {
    dataField: "advert_no",
    text: "Advert No.",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "name",
    text: "Title",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "from_date",
    text: "From Date",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "to_date",
    text: "End Date",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "status",
    text: "Status",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "organization_id",
    text: "Organization",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "sequence_no",
    text: "Sequence No",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "redirect_url",
    text: "Redirect URL",
    sort: true,
    headerStyle: { width: "10%" },
  },
  {
    dataField: "action",
    text: "Action",
    headerStyle: { width: "10%" },
    csvExport: false,
  },
];

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

class Promotions extends PureComponent {
  constructor(props) {
    super(props);
    this.routeChange = this.routeChange.bind(this);
    // this.googleTranslateElementInit =
    //   this.googleTranslateElementInit.bind(this);
    this.search = this.search.bind(this);
    this.state = {
      user_id: 0,
      formData: "",
      emp: "",
      posts: "",
      timeOut: 5000,
      showCloseButton: true,
      progressBar: true,
      position: "top-right",
    };
    this.ochange = this.ochange.bind(this);
    this.oid = 0;
    this.sid = 1;

    this.csvColumns = [
      {
        displayName: "Organization",
        id: "organization_id",
      },
      { displayName: "Sequence No", id: "sequence_no" },
      { displayName: "Redirect URL", id: "redirect_url" },
    ];

    //   submitted: false,
  }

  edit(e) {
    this.props.history.push("/promotions/add/" + e);
  }

  remove(e) {
    var admin_id = localStorage.getItem("uname");
    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 + `organization/deleteAd`, {
          method: "POST",
          body: e,
        })
          .then(
            toastr.success(
              "Success",
              "Promotion Deleted Successfully..!",
              options
            ),
            fetch(
              myConstClass.BASE_URL +
                "organization/getAds/" +
                admin_id +
                "/" +
                this.oid +
                "/" +
                this.sid
            )
              .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();
      }
    });
  }

  // remove(e) {
  //   this.flag = 1;
  //   var admin_id = localStorage.getItem('uname');
  //   const options = {
  //       timeOut: parseInt(this.state.timeOut),
  //       showCloseButton: this.state.showCloseButton,
  //       progressBar: this.state.progressBar,
  //       position: this.state.position
  //     };
  //     this.flag = 1;
  //   confirmAlert({
  //     title: '',
  //     message: 'Are you sure ?',
  //     buttons: [
  //       {
  //         label: 'Yes',
  //         onClick: () =>    fetch(myConstClass.BASE_URL+`announcements/deleteAnnouncement`, {
  //           method: 'POST',
  //           body: e,
  //         }).then(toastr.success(
  //           'Success',
  //           "Announcement Deleted Successfully..!",
  //           options
  //         ), fetch(myConstClass.BASE_URL+'announcements/getAnnouncement/'+admin_id)
  //         .then(response => response.json())
  //         .then(response =>{
  //           let i=1;
  //         response.forEach(element => {
  //           let id=element.uid;
  //         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.uid = i;
  //          i++;
  //         });
  //         this.setState({formData: response})
  //       }).catch(err => console.log(err))
  //         )
  //         .catch()
  //       },
  //       {
  //         label: 'No',
  //         onClick: () => <Redirect to='announcements/listing'  />
  //       }
  //     ]
  //   });
  // }

  ochange(event) {
    var admin_id = localStorage.getItem("uname");
    this.oid = event.target.value;
    fetch(
      myConstClass.BASE_URL +
        "organization/getAds/" +
        admin_id +
        "/" +
        this.oid +
        "/" +
        this.sid
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.status = (
            <div>
              <label
                style={
                  element.color != "" ? { color: "red" } : { color: "black" }
                }
              >
                {element.status}
              </label>
            </div>
          );
          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));
  }

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

  search(event) {
    var admin_id = localStorage.getItem("uname");
    this.sid = event.target.value;
    if (this.sid == null || this.sid == "") {
      this.sid = 0;
    } else {
      this.sid = event.target.value;
    }
    fetch(
      myConstClass.BASE_URL +
        "organization/getAdsOnSearch/" +
        admin_id +
        "/" +
        this.oid +
        "/" +
        this.sid
    )
      .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));
  }
  componentDidMount() {
    // window.googleTranslateElementInit = this.googleTranslateElementInit;
    // const google = window.google;
    // const script = document.createElement("script");
    // script.src =
    //   "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);

    var admin_id = localStorage.getItem("uname");
    if (admin_id == null) {
      this.routeChange();
    }
    document.querySelector(".react-bootstrap-table").style.minHeight = "243px";
    fetch(
      myConstClass.BASE_URL + "organization/get_all_organizations/" + admin_id
    )
      .then((response) => response.json())
      .then((response) => {
        if(admin_id!='0lkuyyyyyyyyyyyyyyyyyyyy666accbnmo')
        {
        response.forEach((element) => {
          this.setState({ organization_id: element.id });
          this.oid = element.id;
        });
        }
        this.setState({ org: response });
      })
      .catch((err) => console.log(err));
    fetch(
      myConstClass.BASE_URL +
        "organization/getAds/" +
        admin_id +
        "/" +
        this.oid +
        "/" +
        this.sid
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.status = (
            <div>
              <label
                style={
                  element.color != "" ? { color: "red" } : { color: "black" }
                }
              >
                {element.status}
              </label>
            </div>
          );
          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));
  }

  // googleTranslateElementInit() {
  //   // / eslint-disable no-new /
  //   const google = window.google;
  //   new google.translate.TranslateElement(
  //     { pageLanguage: "en" },
  //     "google_translate_element"
  //   );
  //   new window.google.translate.TranslateElement(
  //     {
  //       pageLanguage: "pt",
  //       layout: window.google.translate.TranslateElement.FloatPosition.TOP_LEFT,
  //     },
  //     "google_translate_element"
  //   );
  // }

  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 +
        "organization/getAds/" +
        admin_id +
        "/" +
        this.oid +
        "/" +
        this.sid
    )
      .then((response) => response.json())
      .then((response) => {
        let i = 1;
        response.forEach((element) => {
          let id = element.id;
          element.status = (
            <div>
              <label
                style={
                  element.color != "" ? { color: "red" } : { color: "black" }
                }
              >
                {element.status}
              </label>
            </div>
          );
          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");
    const { org, emp } = this.state;
    const csvColumns = this.csvColumns;
    const csvData = this.state.formData;
    let fileName = "Promotions_" + new Date().getTime() + ".csv";

    return (
      <Container fluid>
        <Header>
          {/* <div id="google_translate_element"></div> */}
          <br />
          <HeaderTitle>Adverts List</HeaderTitle>

          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            {/* <BreadcrumbItem>
              <Link to="/dashboard">measures</Link>
            </BreadcrumbItem> */}
            <BreadcrumbItem active>Adverts List</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;ADD
            </button>
          </Breadcrumb>
          {/* <span >ADD</span> */}
        </Header>

        <Card>
          <AvForm id="sform">
            <Row className="f_class_promo">
              <div class="col-md-4"></div>
              <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_promo_label">
                    Search
                  </Label>
                  <AvInput
                    name="search"
                    className="search_promo"
                    onChange={this.search}
                    type="text"
                    id="example"
                  />
                </AvGroup>
              </div>
            </Row>
          </AvForm>
          <br />

          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV
          >
            {(props) => (
              <div>
                <CardHeader>
                  {/* <div className="float-right pull-right"> */}

                  {/* <div class="float-right pull-right" style={{ left: '398px',top: '-21px'}}>
                    <CsvDownloader
                    className="csv"
                    style={{float:'right',backgroundColor:"#4B0082"}}
                    filename={fileName}
                      columns={csvColumns}
                      datas={csvData}
                    text="Export" /></div> */}

                  {/* <MyExportCSV {...props.csvProps} /> */}
                  {/* </div> */}
                  {/* <CardTitle tag="h5">Export CSV</CardTitle>
                  <h6 className="card-subtitle text-muted">
                    Exportable CSV by react-bootstrap-table2
                  </h6> */}
                </CardHeader>
                <CardBody>
                  <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                    {/* With AvGroup AvInput and AvFeedback to build your own */}
                    <Row>
                      <div class="col-md-4">
                        <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>
                      <div class="col-md-4">
                        <AvGroup>
                          <AvField
                            type="select"
                            name="organization_id"
                            label="Select Status"
                            onChange={this.status_change}
                            value={this.sid}
                          >
                            <option value={1}>Active</option>
                            <option value={2}>In-Active</option>
                          </AvField>
                        </AvGroup>
                      </div>
                    </Row>
                    <Row>
                      <div class="col-md-4">
                        <Label for="example" className="search_title"></Label>
                        <br />
                        <MyExportCSV {...props.csvProps} />
                      </div>
                      {/* <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_title">Search</Label>
                  <AvInput name="search" className="search" onChange={this.search} type="text" id="example"/>
                </AvGroup>
              </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 Promotions;
