import React,{ PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from '../../constant.js';
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 css
import swal from 'sweetalert';

import {
  AvForm,
  AvGroup,
  AvInput} from "availity-reactstrap-validation";
  const { SearchBar } = Search;
const tableColumns = [ 
    {
      dataField: "name",
      text: "Holiday Name",
      sort: true,
      headerStyle: { width:"10%" }
    },
    {
      dataField: "date",
      text: "date",
     // 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 Holidays 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"
      }
    
     

      //for export
      // this.csvColumns = [
      //   {
      //      displayName: "Organization", 
      //      id: "organization_id"
      //  },
      //   { displayName: 'Title',
      //   id: "title"
      // },  
      //   { displayName: "Created At", 
      //   id: "created_at" },
    
      // ];

    //   submitted: false,
    }

    edit(e) { 
        this.props.history.push('/settingsholidays/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/deleteHoliday/`+admin_id, {
        method: 'POST',
        body: e,
      }).then(toastr.success(
        'Success',
        "Holiday Deleted Successfully..!",
        options
      ),   
      fetch(myConstClass.BASE_URL+'organization/getPublicHolidays/'+admin_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))
      )
      .catch();
    }
        });    
      }


      search(event){
        this.setState({formData: []})
        var admin_id= localStorage.getItem('uname'); 
        this.sid = event.target.value;
        fetch(myConstClass.BASE_URL+'organization/getPublicHolidays/'+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))
            
      }
  

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

    //     window.googleTranslateElementInit = this.googleTranslateElementInit;
    // const script = document.createElement("script");
    // script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
    // script.async = true;
    // document.body.appendChild(script);  

        document.querySelector('.react-bootstrap-table').style.minHeight  = "243px";
        var admin_id= localStorage.getItem('uname'); 
        if(admin_id == null){
          this.routeChange();
        }
        fetch(myConstClass.BASE_URL+'organization/getPublicHolidays/'+admin_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))
    }

      // 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 {formData} = this.state; 

      //for export csv
     
      return(
      <Container fluid>
        <Header>
          {/* <div  id="google_translate_element"></div><br/> */}
          <HeaderTitle>Public Holidays List</HeaderTitle>
    
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            
            <BreadcrumbItem active>Public Holidays 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> */}
            {(admin_id !='0' ) ?
            <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_announce">
         <div class="col-md-4"></div>
          <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_an_label" >Search</Label>
                  <AvInput name="search" className="search_announce" onChange={this.search} type="text" id="example"/>
                </AvGroup>
              </div><br/>
            </Row>
           </AvForm>
         

          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV
            search
          >
            {props => (
              <div>
                <CardHeader>
            
                </CardHeader>
                <CardBody>
                <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
               
               
             
           <Row>
           <div class="col-md-4">
           <Label for="example" className="search_title"></Label>
           <MyExportCSV {...props.csvProps} />
           </div>
           {/* <div>
           <Label for="example"> </Label>
                        <SearchBar
                          {...props.searchProps}
                          placeholder="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 Holidays;