import React,{PureComponent} from "react";
import { Link } from "react-router-dom";
import InputMask from "react-input-mask";
import DatePicker from "react-datepicker";
import TimePicker from 'react-time-picker';
import "react-datepicker/dist/react-datepicker.css";
import ReactQuill from "react-quill";
import dateFormat from 'dateformat';
import {
  Breadcrumb,
  BreadcrumbItem,Row,Col,
  Card,
  Input,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  Button,
  Label,
  FormGroup,
  CustomInput
} from "reactstrap";

import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";

import * as myConstClass from '../../constant.js';
import $ from 'jquery'; 
import { toastr } from "react-redux-toastr";
import * as Icon from "react-feather";
import {
  AvForm,
  AvField,
  AvGroup,
  AvInput,
  AvFeedback,
  AvRadioGroup,
  AvRadio,
  AvCheckboxGroup,
  AvCheckbox
} from "availity-reactstrap-validation";



class Validation extends PureComponent {
    constructor(props) {
      super(props);
      this.routeChange = this.routeChange.bind(this);
      //this.googleTranslateElementInit = this.googleTranslateElementInit.bind(this);
      // state = {
      //   startDate: new Date()
      // };
      this.state = {
        user_id:'0',
        units:'',
        org:'',
        emp:'',
        date:'',
        startDate: new Date(),
        time: '10:00',
        timezones:'',
        formData:{
          employee_id: '',
          date:'',
          attendance_date: '',
          clock_in: '',
          clock_out: '',
          timezone:'',
        },
        submitted: false,
        timeOut: 5000,
        showCloseButton: true,
        progressBar: true,
        position: "top-right"
      }
     
      this.options = {
        timeOut: parseInt(this.state.timeOut),
        showCloseButton: this.state.showCloseButton,
        progressBar: this.state.progressBar,
        position: this.state.position
      };
    
    }


    handleTextChange = (announcement) => {  
      this.setState({ announcement });
      };
      handleChange = date => {
        this.setState({ date });
    };
    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();
      }
        const answer_array = this.props.location.pathname.split('/');
        //alert(answer_array['3']);
        if(answer_array['3']){  
            this.state.user_id = answer_array['3'];
            fetch(myConstClass.BASE_URL+'organization/getEmpGroupInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{this.setState({formData: response})}).catch(err => console.log(err));
        }
        var admin_id= localStorage.getItem('uname'); 
      }


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

      handleValidSubmit = () => {
        var admin_id= localStorage.getItem('uname'); 

        this.setState({ submitted: true }, () => {  
            setTimeout(() => this.setState({ submitted: false }), 5000);
           
            fetch(myConstClass.BASE_URL+`organization/add_emp_group/`+admin_id+'/'+this.state.user_id, {
                    method: 'POST',
                    body: JSON.stringify($('#pform').serializeArray()),
                    // contentType: "application/json; charset=utf-8",
                  }).then(response =>  response.json()).then((response) => {
                    if(response == true){
                      (this.state.user_id =='0' ) ?
                      toastr.success(
                        'Success',
                        "Employee Group Created Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Employee Group Updated Successfully..!",
                        this.options
                      );
    
                      this.props.history.push('/employee_groups/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not create Employee Group ..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }

      render () { 
        const { formData,units,submitted} = this.state;
        let date;
        if(this.state.user_id !=='0'){ 
          date = formData.date;
        } else { 
          date =  this.state.date;
        }
      
        return(
        <Container fluid>
          <Header><div  id="google_translate_element_1"></div><br/>
            <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/employee_groups/listing">Employee Groups List</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</BreadcrumbItem>
            </Breadcrumb>
          </Header>    
          <Card>
    
            <CardBody>
              <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>
                <Row>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Title</Label>
                    <AvInput name="title" id="example" required value={formData ? formData.title:''}/>
                    <AvFeedback>Enter Title !</AvFeedback>
                  </AvGroup>
                  </Col>
                  <Col lg={6}>
                    <AvGroup>
                      <Label for="example">Description</Label>
                      <AvInput name="description" id="example" required value={formData ? formData.description:''}/>
                      <AvFeedback>Enter Description !</AvFeedback>
                    </AvGroup>
                  </Col>
                </Row>
                <FormGroup>
                <Link to="/employee_groups/listing" style={{margin:"0rem 1.50rem 1.50rem 0rem",border: "#6f42c1 1px solid",color: "#6f42c1",padding: "0.10rem 0.90rem 0.30rem 0.90rem",textDecoration: 'none',borderRadius:'0.2rem'}}>Cancel</Link>
                {(this.state.user_id !='0' ) ? <Button disabled={submitted}>{
                              (submitted && 'Your form is submitted!')
                              || (!submitted && 'Update')
                          }</Button> : <Button disabled={submitted}>{
                              (submitted && 'Your form is submitted!')
                              || (!submitted && 'Add')
                          }</Button> }
                  
                   </FormGroup>
              </AvForm>
            </CardBody>
          </Card>
        </Container>
      )
      }



    }
 export default Validation;


