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 {
  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.handleAddMore = this.handleAddMore.bind(this);
      this.state = { file: ''};
      this.state = {file: '',imagePreviewUrl: ''};
      this.state = {
        user_id:'0',
        units:'',
        org:'',
        emp:'',
        customDiv:[],
        seqarr:[],
        formData:[],
        startDate: new Date(),
        time: '10:00',
        timezones:'',
        formData:{
         
          employee_id: '',
          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
      };
    
    }

    _handleImageChange(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(){    
      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/getAdInfo/'+answer_array['3'])
        .then(response => response.json())
        .then(response =>{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({ organization: response }); }).catch(err => console.log(err));      
      }

      handleAddMore = () => {
      //alert('in');
      let cDivs = this.state.customDiv;
      cDivs.push('newDiv')
      this.setState({customDiv: cDivs });
      }

      handleSeqNohange=(event)=>{
      var arr=[]; 
      $("input:text[name^='sequence_no_']").each(function(v){       
      arr.push($( this ).val());
      }); 
      const { seqarr } = this.state;
      seqarr['seqarr'] = arr;
      this.setState({ seqarr });
      }
    
      handleValidSubmit = () => { 
        var admin_id= localStorage.getItem('uname'); 
        const { seqarr } = this.state;
        alert(seqarr['seqarr']);
        this.setState({ submitted: true }, () => {  
            setTimeout(() => this.setState({ submitted: false }), 5000);
            const data = new FormData() 
            data.append('file', this.state.file);
            // data.append('seqarr',JSON.stringify(seqarr['seqarr']));     
            data.append('formdata',JSON.stringify($('#pform').serializeArray()));     
            fetch(myConstClass.BASE_URL+`organization/add_more_ads/`+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',
                        "Promotion Added Successfully..!",
                        this.options
                      ) : toastr.success(
                        'Success',
                        "Promotion Updated Successfully..!",
                        this.options
                      );
                      this.props.history.push('/promotions/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not Add Promotion ..!",
                        this.options
                      )
                    }
                  })
            .catch();
         });
      }

      render () { 
        const { formData,units,submitted,seqarr} = this.state;
        const { organization} = this.state;
        let {imagePreviewUrl} = this.state;
        let $imagePreview = null;
        let file_link;
        let img;
        if(this.state.user_id !=='0'){
        //  file_link = `https://alpha.workzoneplus.com/backend/uploads/banners/`+formData.image;
         file_link = `https://beta.workzoneplus.com/backend/uploads/banners/`+formData.image;
        // file_link = `http://localhost/workzone/backend/uploads/banners/`+formData.image;
         img =  <img src={file_link}  style={{width: '50px',height:'50px'}}/>;
        } else {
         file_link = ''; 
         img = '';
        }
      
        if (imagePreviewUrl) {
            $imagePreview = (<img src={imagePreviewUrl} style={{width: '50px',height:'50px'}}/>);   
            img = '';
          } else {
            $imagePreview = (<div className="previewText"></div>);   
          }
        return(
        <Container fluid>
          <Header>
            <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>
            <Breadcrumb>
              <BreadcrumbItem>
                <Link to="/dashboard">Dashboard</Link>
              </BreadcrumbItem>
              <BreadcrumbItem>
                <Link to="/promotions/listing">Promotions List</Link>
              </BreadcrumbItem>
              <BreadcrumbItem active>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</BreadcrumbItem>
            </Breadcrumb>
          </Header>    
          <Card>
            {/* <CardHeader>
              <CardTitle tag="h5">Availity Validation</CardTitle>
              <h6 className="card-subtitle text-muted">
                Form validation by availity-reactstrap-validation
              </h6>
            </CardHeader> */}
            <CardBody>
           
              <AvForm id="pform" onValidSubmit={this.handleValidSubmit}>   
                    
                {/* With AvGroup AvInput and AvFeedback to build your own */}
                <Row>
                <Col lg={6}>
                <AvGroup>
                  {/* <AvInput name="employee_id" id="example" required value={formData ? formData.employee_id:''}/>
                  <AvFeedback>Enter Employee ID!</AvFeedback> */}
                 <AvField
                  type="select"
                  name="organization_id"
                  label="Select Organization"
                  value={formData ? formData.organization_id:''}
                >
                  {organization ?  organization.map((cell, i) => {
                  return(<option value={cell.id}>{cell.title}</option>)
                  }) : ''}       
                </AvField>
                </AvGroup>
               </Col>               
               <Col lg={6}>  
                <AvGroup>
                  <Label for="example">Sequence No</Label>
                  <AvInput type="number" name="sequence_no_"  id="example" required value={formData ? formData.sequence_no:''}/>
                  <AvFeedback>Enter Sequence No..!</AvFeedback>
                </AvGroup>
                </Col>      
              </Row>
            <Row>
           <Col lg={6}>  
           <AvGroup>
                  <Label for="example">Redirect URL</Label>
                  <AvInput  name="redirect_url" id="example" required value={formData ? formData.redirect_url:''}/>
                  <AvFeedback>Enter Redirect URL..!</AvFeedback>
                </AvGroup>
           </Col>
           <Col lg={6}>  
           <AvGroup>
                <Label for="example">Status</Label>
                <Input
                        type="select"
                        id="exampleCustomSelect"
                        name="status"
                        className="mb-3"
                    >
                        <option value="1">Active</option>
                        <option value="2">In-Active</option>
                    </Input>
                </AvGroup>
            </Col>
           </Row>
            <Row>
            <Col lg={6}>
            <Label for="example">Select Image</Label>    
            <Input type="file"
             name="image"
             id= 'file'
             onChange={(e)=>this._handleImageChange(e)} /><br/> <br/>   
             {img}<br/> <br/>
              <div className="imgPreview">
                 {$imagePreview}              
               </div>
            </Col><br/><br/><br/><br/>
           </Row><br/>
           <button class="mr-1 mb-1  btn-outline-secondary" onClick={this.handleAddMore} style={{float:'right ',margin:'auto'}}><Icon.PlusCircle />&nbsp;&nbsp;ADD</button>
            
           {/* <button   onClick={this.handleAddMore} style={{float:'right ',margin:'auto'}}> Add More<i></i></button><br/><br/> */}
           {this.state.customDiv.map((cdiv, i) => {
           return(
                <Row>
                 <div className="col-md-6 manage-food-modal" key={cdiv} data-common-measure-id="temp-`${i}`">
                  <Col lg={6}>  
                   <AvGroup>  
                     <Label for="example">Sequence No</Label>                   
                      <AvInput type="text" name={"sequence_no_"+i} id="example" onChange={this.handleSeqNohange} required value= {formData ? seqarr.seqarr[i] :''}/>
                     <AvFeedback>Enter Sequence No..!</AvFeedback>
                   </AvGroup>
                 </Col>  
                </div>
              </Row>
              );
           })}
          {/* <Row>
                  <Col lg={6}>
                <AvGroup>
                  <Label for="example">Sequence</Label>
                  <AvInput name="sequence" value={formData ? formData.sequence:''} id="example" validate={{
                  required: {value: true},
                  pattern: {value: '^[0-9]+$'},
                  
                }} />
                  <AvFeedback>Enter Number</AvFeedback>
                </AvGroup>
                </Col>
                </Row> */}
               
      
                <FormGroup>
                <Link to="/promotions/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;


