import React,{ PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import {
  Breadcrumb,Row,Label,
  BreadcrumbItem, Button,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container, 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 { toastr } from "react-redux-toastr";
import CsvDownloader from 'react-csv-downloader';
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 {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox
} from "availity-reactstrap-validation";
import './common.scss';
const tableColumns = [
  {
    dataField: "name",
    text: "Name",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "email",
    text: "Email ",
    sort: true,
    headerStyle: { width:"15%" }
  },
  {
    dataField: "mobile_no",
    text: "Mobile No",
    sort: true,
    headerStyle: { width:"10%" }
  },
  {
    dataField: "gender",
    text: "Gender",
    sort: true,
    headerStyle: { width:"10%" }
    
  },
  {
    dataField: "status",
    text: "Status",
    headerStyle: { width:"10%" }
  },
  {
    dataField: "date",
    text: "Created Date",
    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 Hradmin 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 No',
        id: "email"
      },  
        { displayName: "Mobile No", 
        id: "mobile_no" },
        { displayName: "Gender", 
        id: "gender" },
       
        { displayName: "Status", 
        id: "status" },
      ];
    }
 

    edit(e) { 
        this.props.history.push('/hradmin/add/'+e);
      }

      // remove(e) { 
      //   this.flag = 1;
      //   var admin_id = sessionStorage.getItem('username'); 
      //   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+`user/deleteAdmin`, {
      //           method: 'POST',
      //           body: e,
      //         }).then(toastr.success(
      //           'Success',
      //           "HR Admin Deleted Successfully..!",
      //           options
      //         ),
      //         fetch(myConstClass.BASE_URL+'user/getAdmin/0')
      //         .then(response => response.json())
      //         .then(response =>{
      //           let i=1;
      //           response.rows.forEach(element => {
      //           element.action = <div><i id={element.id} className="fa fa-remove ptr_css" onClick={() =>this.remove(element.id)}></i><i id={element.id} className="fa fa-edit ptr_css" onClick={() =>this.edit(element.id)}></i></div>;
      //            i++;
      //           });
      //           this.setState({posts: response})
      //         })
      //         .catch(err => console.log(err))
      //         )
      //         .catch()
      //       },
      //       {
      //         label: 'No',
      //         onClick: () => <Redirect to='/hradmin/listing'  />
      //       }
      //     ]
      //   });
      // }



      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/deleteAdmin`, {
        method: 'POST',
        body: e,
      }).then(toastr.success(
        'Success',
        "HR Admin Deleted Successfully..!",
        options
      ),
    
      fetch(myConstClass.BASE_URL+'user/getAdmin/0')
      .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(){

    //     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/getAdmin/0')
      .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))
      }

      // 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')
      // }



      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+'/user/getAdminOnSearch/'+admin_id+'/'+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))
      }

      render() { 

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


        return(
      <Container fluid>
        <Header><div  id="google_translate_element"></div><br/>
          <HeaderTitle>Hr Admin List</HeaderTitle>
    
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            {/* <BreadcrumbItem>
              <Link to="/dashboard">measures</Link>
            </BreadcrumbItem> */}
            <BreadcrumbItem active>Hr Admin 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_hr">
         <div class="col-md-4"></div>
          <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_hr_label" >Search</Label>
                  <AvInput name="search" className="search_hr" 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">
                  
                    <MyExportCSV {...props.csvProps} /> */}

                    {/* <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> */}

                  {/* </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 Hradmin;
