import React,{ PureComponent } from "react";
import { Link } from "react-router-dom";
import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import {
  Breadcrumb,
  BreadcrumbItem, Buttonn,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 './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 { 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";
const tableColumns = [ 
    {
      dataField: "organization_id",
      text: "Organization",
      sort: true,
      headerStyle: { width:"10%" }
    },
    {
      dataField: "title",
      text: "Title",
      sort: true,
      headerStyle: { width:"10%" }
    },
    {
      dataField: "created_at",
      text: "Created At",
      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 Announcements 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;

      //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('/announcements/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+`announcements/deleteAnnouncement/`+admin_id, {
        method: 'POST',
        body: e,
      }).then(toastr.success(
        'Success',
        "Announcement Deleted Successfully..!",
        options
      ),   
      fetch(myConstClass.BASE_URL+'announcements/getAnnouncement/'+admin_id+'/'+this.oid)
        .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+'announcements/getAnnouncement/'+admin_id+'/'+this.oid)
        .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))
            
      }

      search(event){
        var admin_id= localStorage.getItem('uname'); 
        this.sid = event.target.value;
        fetch(myConstClass.BASE_URL+'announcements/getAnnouncementOnSearch/'+admin_id+'/'+this.sid+'/'+this.oid)
        .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 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);  

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

    fetch(myConstClass.BASE_URL+'organization/get_all_organizations/'+admin_id)
    .then(response => response.json())
    .then(response =>{this.setState({org: 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 ,formData} = this.state; 

      //for export csv
      const csvColumns= this.csvColumns;
      const csvData =this.state.formData;
      let fileName = 'Announcements_'+new Date().getTime()+'.csv';




        return(
      <Container fluid>
        <Header>
          {/* <div  id="google_translate_element"></div> */}
          <HeaderTitle>Announcements List</HeaderTitle>
    
          <Breadcrumb>
            <BreadcrumbItem>
              <Link to="/dashboard">Dashboard</Link>
            </BreadcrumbItem>
            {/* <BreadcrumbItem>
              <Link to="/dashboard">measures</Link>
            </BreadcrumbItem> */}
            <BreadcrumbItem active>Announcements 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>
             <br/>
            </Row>
           </AvForm>
         

          <ToolkitProvider
            keyField="name"
            data={this.state.formData}
            columns={tableColumns}
            exportCSV
          >
            {props => (
              <div>
                <CardHeader>
            
                </CardHeader>
                <CardBody>
                <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
               
               {/* With AvGroup AvInput and AvFeedback to build your own */}
               <Row>
             <div class="col-md-4">
             {(admin_id == 0 ) ?<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>
           </Row>
           <Row>
           <div class="col-md-4">
           <Label for="example" className="search_title"></Label>
           <MyExportCSV {...props.csvProps} />
           </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>
             {/* <div class="col-md-4"></div>
              <div class="col-md-4">
                <AvGroup>
                  <Label for="example" className="search_title_an">Search</Label>
                  <AvInput name="search" className="search_announce" 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 Announcements;