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,Label,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container, Modal,
  ModalBody,
  ModalFooter,
  ModalHeader,
} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";
import './common.scss';
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 CsvDownloader from 'react-csv-downloader';
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox
} from "availity-reactstrap-validation";
import swal from 'sweetalert';
const tableColumns = [
    {
      dataField: "name",
      text: "Name",
      sort: true,
      headerStyle: { width:"15%" }
    },
    {
      dataField: "email",
      text: "Email",
      sort: true,
      headerStyle: { width:"20%" }
    },
    // {
    //   dataField: "position",
    //   text: "Position",
    //   sort: true,
    //   headerStyle: { width:"10%" }
    // },
    {
      dataField: "organization",
      text: "Organization",
      sort: true,
      headerStyle: { width:"15%" }
      
    },
    {
      dataField: "mobile_no",
      text: "Mobile No",
      headerStyle: { width:"15%" }
    },
    {
      dataField: "created_at",
      text: "Created At",
      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 Signup 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:'',
        timeOut: 5000,
        showCloseButton: true,
        progressBar: true,   
        position: "top-right"
      }

      this.csvColumns = [
        
        { displayName: 'Name',
        id: "name"
      }, 
      { displayName: "Email", 
      id: "email" }, 
      
        { displayName: "Position", 
        id: "position" },
        { displayName: "Organization", 
        id: "organization" },
        { displayName: "Mobile No", 
        id: "mobile_no" },
        { displayName: "Created At", 
        id: "created_at" },
      
      ];

    }

 view(e) { 
   this.props.history.push('/signup/view/'+e);
}

// remove(e) {  
//     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/deleteRequest`, {
//     method: 'POST',
//     body: e,
//   }).then(toastr.success(
//     'Success',
//     "Request Deleted Successfully..!",
//     options
//   ),
//   fetch(myConstClass.BASE_URL+'user/getRequests/')
//   .then(response => response.json())
//   .then(response =>{
//     let i=1;  
//   response.forEach(element => {
//     let id=element.id;
//   element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(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) { 
    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+`/user/deleteRequest`, {
    method: 'POST',
    body: e,
  }).then(toastr.success(
    'Success',
    "Request Deleted Successfully..!",
    options
  ),

  fetch(myConstClass.BASE_URL+'user/getRequests')
  .then(response => response.json())
  .then(response =>{
    let i=1;  
  response.forEach(element => {
    let id=element.id;
  element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(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();
}
    });

  
  }


  search(event){
    var admin_id= localStorage.getItem('uname'); 
    this.sid = event.target.value;
    fetch(myConstClass.BASE_URL+'user/getRequestsOnSearch/'+this.sid )
  .then(response => response.json())
  .then(response =>{
    let i=1;  
  response.forEach(element => {
    let id=element.id;
  element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(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('/');
  }
  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+'user/getRequests')
  .then(response => response.json())
  .then(response =>{
    let i=1;  
  response.forEach(element => {
    let id=element.id;
  element.action = <div><Icon.Eye style={{margin:'0px 15px 0px 0px',cursor:'Pointer'}} onClick={() =>this.view(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')
  // }

  render() { 

    var admin_id= localStorage.getItem('uname'); 
    const { org,emp} = this.state; 
    const csvColumns= this.csvColumns;
    const csvData =this.state.formData;
    let fileName = 'SignUp_Requests_'+new Date().getTime()+'.csv'


    return(
  <Container fluid>
    <Header><div  id="google_translate_element"></div><br/>
      <HeaderTitle>SignUp Requests</HeaderTitle>

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        {/* <BreadcrumbItem>
          <Link to="/dashboard">measures</Link>
        </BreadcrumbItem> */}
         <BreadcrumbItem active>SignUp Requests</BreadcrumbItem>
        {/*<button class="mr-1 mb-1 btn btn-outline-secondary" onClick={() =>this.view(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_signup">
         <div class="col-md-4"></div>
          <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_signup_label" >Search</Label>
                  <AvInput name="search" className="search_signup" 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><br/> */}
              {/* <CardTitle tag="h5">Export CSV</CardTitle>
              <h6 className="card-subtitle text-muted">
                Exportable CSV by react-bootstrap-table2
              </h6> */}
            </CardHeader>
            <CardBody>
            <AvForm id="pform">
                <Row>
                <div class="col-md-4">
                <Label for="example" className="search_title"></Label>
                <MyExportCSV {...props.csvProps} /><br/>
                </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>
              <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 Signup;