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 Select from "react-select";
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 = { file: ''};
      this.state = {
        user_id:'0',
        units:'',
        org:'',
        emp:'',
        date:'',
        startDate: new Date(),
        time: '10:00',
        timezones:'',
        complaint_against:[],
        formData_against:'',
        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 });
    };

    handleComplaintChange = (complaint_against) => {
      this.setState({ complaint_against });
    }
    onDocChangeHandler(e) {
      e.preventDefault();
      let reader = new FileReader();
      let file = e.target.files[0];
      reader.onloadend = () => {
        this.setState({
          file: file,
          // imagePreviewUrl: reader.result
        });
      }
      reader.readAsDataURL(file)
    }


    
    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('/');
    
        if(answer_array['3']){  
            this.state.user_id = answer_array['3'];
            fetch(myConstClass.BASE_URL+'user/getComplaintInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{ this.setState({formData: response})}).catch(err => console.log(err));
              
            fetch(myConstClass.BASE_URL+'user/getComplaintAgainstInfo/'+answer_array['3'])
            .then(response => response.json())
            .then(response =>{
              let i=1;  
              response.forEach(element => {
                let id=element.id;
                let name=element.first_name+' '+element.last_name;
                this.setState({complaint_against:[{ value:id, label:name}]});   
               // console.log(element);
               element.id = i;
               i++;
              });
              // formData ? formData.complaint_against:''
              // this.setState({response.complaint_against: complaint_against})
              // this.setState({complaint_against:[{ value:response.id, label:response.first_name+' '+response.last_name }]});   
              this.setState({formData_against: response})}).catch(err => console.log(err));
            
          }
 
      


        fetch(myConstClass.BASE_URL+'attendance/get_all_employees/'+admin_id)
        .then(response => response.json())
        .then(response =>{this.setState({emp: response})}).catch(err => console.log(err))    
      }


      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);
            const data = new FormData() 
            data.append('file', this.state.file);
            data.append('formdata',JSON.stringify($('#pform').serializeArray()));  
            fetch(myConstClass.BASE_URL+`user/add_complaint/`+admin_id+'/'+this.state.user_id, {
                    method: 'POST',
                    body:data,
                    // contentType: "application/json; charset=utf-8",
                  }).then(response =>  response.json()).then((response) => {
                    if(response == true){
                      (this.state.user_id =='0' ) ?
                      toastr.success(
                        'Success',
                        "Complaint Created Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Complaint Updated Successfully..!",
                        this.options
                      );
    
                      this.props.history.push('/complaints/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not create Complaint ..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }

      render () { 
        const { formData,units,submitted,formData_against} = this.state;
        const { emp,complaint_against} = this.state;
        var admin_id= localStorage.getItem('uname'); 
        let date;
        if(this.state.user_id !=='0'){ 
          date = formData.date;
        } else { 
          date =  this.state.date;
        }
        let doc_file_link;
        let c_file;
        let c_file_title
       doc_file_link = `https://beta.workzoneplus.com/backend/uploads/complaints/`+'/'+admin_id+'/'+formData.document;
       if(formData.document){
        c_file_title =  "Uploaded Document : ";
       c_file = <a href={doc_file_link} target="_blank">Document</a>;   
      } else {
        c_file_title =  '';
        c_file ='';
      }

       let options; 
        // let options_against;
        if(this.state.user_id !=='0'){ 
          // options_against =   formData_against ? formData_against.map((cell1, i) => {
          //   return { value: cell1.id, label: cell1.first_name+' '+cell1.last_name };
          // }):emp ?  emp.map((cell, i) => {
           
          //   return { value: cell.id, label: cell.first_name+' '+cell.last_name };
          //   // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
          //   }) : '';
        }
        // this.setState({complaint_against:[{ value:response.id, label:response.first_name+' '+response.last_name }]});   

           options =   emp ?  emp.map((cell, i) => {
            return { value: cell.id, label: cell.first_name+' '+cell.last_name };
            // return( value: cell.TimeZone, label: cell.TimeZone+'(UTC '+cell.UTC_offset+')' }
            }) : '';

           
      
        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="/complaints/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>
                  <AvField
                  type="select"
                  name="complaint_from"
                  label="Complaint From"
                  value={formData ? formData.complaint_from:''}
                >
                  {emp ?  emp.map((cell, i) => {
                  return(<option value={cell.id}>{cell.first_name}  {cell.last_name}</option>)
                  }) : ''}       
                </AvField>
                </AvGroup>
                </Col>
                <Col lg={6}>
                <Label for="example">Complaint Against</Label>
                  <Select
                   //label="Complaint Against"
                   value={complaint_against}
                  name="complaint_against"
                  className="react-select-container"
                  classNamePrefix="react-select"
                  options={options}
                  onChange={this.handleComplaintChange}
                
                  isMulti
                />
                <AvGroup>
                

                  {/* <AvField
                  type="select"
                  name="complaint_against"
                  label="Complaint Against"
                  value={formData ? formData.complaint_against:''}
                >
                  {emp ?  emp.map((cell, i) => {
                  return(<option value={cell.id}>{cell.first_name}  {cell.last_name}</option>)
                  }) : ''}       
                </AvField> */}
                </AvGroup>
                </Col>
                <Col lg={6}>
                            <AvGroup>
                                <Label for="example">Complaint Date (DD/MM/YYYY)</Label> <br/>
                                {(this.state.user_id !='0' ) ? <DatePicker
                                name="date"
                                selected= {this.state.date}
                                onChange={this.handleChange}                
                                dateFormat="dd-mm-yyyy"
                                showYearDropdown
                                // disabled
                                yearDropdownItemNumber={15}
                                scrollableYearDropdown
                                className="re_date"               
                                dateFormat="dd-MM-yyyy"
                                // style={{width: '352px',height:'32px'}}
                                value= { this.state.date || formData.date}
                                /> 
                              :
                              
                              <DatePicker
                              name="date"
                              selected= {this.state.date}
                              onChange={this.handleChange}                
                              showYearDropdown
                              // disabled
                              yearDropdownItemNumber={15}
                              scrollableYearDropdown
                              className="re_date"               
                              dateFormat="dd-MM-yyyy"
                              value= { this.state.date }         
                              /> 
                              }   
                   </AvGroup>
                </Col>
                <Col lg={6}>
                  <AvGroup>
                    <Label for="example">Subject</Label>
                    <AvInput name="subject" id="example" required value={formData ? formData.subject:''}/>
                    <AvFeedback>Enter Subject !</AvFeedback>
                  </AvGroup>
                  </Col> 
                <Col lg={6}>  
                <AvGroup>
                  <Label for="example">Description</Label>
                  <AvInput type="textarea" name="description" id="example" required value={formData ? formData.description:''}/>
                  <AvFeedback>Enter Description..!</AvFeedback>
              </AvGroup>
             </Col>
             <Col lg={6}>
              <AvGroup>
                <Label for="example">Action Taken</Label>
                <AvInput type="textarea" name="action_taken" id="example" required value={formData ? formData.action_taken:''}/>
                <AvFeedback>Enter Action Taken !</AvFeedback>
              </AvGroup>
              </Col> 
                </Row>
                <Row>
                <Col lg={12}>
                <AvGroup>
                  <Label for="example">Upload Document</Label>   <br/> 
                    <input type="file"  id= 'file1' name="document" onChange={(e)=>this.onDocChangeHandler(e)} />   
                    </AvGroup> 
                    </Col>
                  </Row>
                  {c_file_title} {c_file}<br/><br/>
                <FormGroup>
                <Link to="/complaints/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;


