import React,{PureComponent} from "react";
import { Link } from "react-router-dom";
import { Tabs,Tab } from 'react-bootstrap';
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 paginationFactory from "react-bootstrap-table2-paginator";
//import { CircularProgressbar } from 'react-circular-progressbar';
import Header from "../../components/Header";
import HeaderTitle from "../../components/HeaderTitle";
import BootstrapTable from "react-bootstrap-table-next";
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";
//import './common.scss';
//  const [fields, file,sequence_no,redirect_url,status] =  this.state([{ value: null }]);

class Validation extends PureComponent {
    constructor(props) {
      super(props);
      this.routeChange = this.routeChange.bind(this);
      this.handleAddShareholder = this.handleAddShareholder.bind(this);
      this.state = { file: ''};
      this.state = {file: '',imagePreviewUrl: ''};
      // this.state = { inputs: ['input-0'] };
      this.state = {
        user_id:'0',
        units:'',
        org:'',
        emp:'',
        name: "",
        customDiv: [],
        
        sequence_no: [],
        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
      };
      // this.handleAddShareholder = this.handleAddShareholder.bind(this);
      // this.handleChange = this.handleChange.bind(this);
      this.handleMeasure = this.handleMeasure.bind(this);
    }

    _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');
      //alert(admin_id) ;
      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})
              let cDivs = [];
              response.sequence_no.map(() => {
            //     //let cDivs = this.state.customDiv;
                cDivs.push('newDiv')
                 this.setState({customDiv: cDivs })
               })
               })
            
             .then(response =>{this.setState({formData: response})}).catch(err => console.log(err));
            
            
            // .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));      
      }
    
      handleSinChange=(event)=>{
        var arr=[];
      $("input:text[name^='sinname_']").each(function(v){ 
        //alert($( this ).val() );
        arr.push($( this ).val());
      });
        const { formData } = this.state;
        formData['sequence_no'] = arr;
        this.setState({ formData });
      }
      //  handleAdd() {
      //   const values = [file,sequence_no,redirect_url,status];
      //   values.push({ value: null });
      //   // setFields(file,sequence_no,redirect_url,status);
      // }
      handleValidSubmit = (e) => {
        e.preventDefault();
          const { formData,units,submitted} = this.state;
        //  alert(`Incorporated: ${formData} with ${units.length} shareholders`);
       
        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+`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('/morepromotions/listing');
                    } else{
                      toastr.error(
                        'Error',
                        "Can not Add Promotion ..!",
                        this.options
                      )
                    }
                  })
                  .catch();
         });
      }
      handleMeasure = () => {
        //alert('in');
        let cDivs = this.state.sequence_no;
        cDivs.push('newDiv')
        this.setState({sequence_no: cDivs })
      }
      // handleNameChange = evt => {
      //   this.setState({ org: evt.target.value });
      // };
      // handleShareholderNameChange = idx => evt => {
      //   const newShareholders = this.state.sequence_no.map((shareholder, sidx) => {
      //     if (idx !== sidx) return shareholder;
      //     return { ...shareholder, name: evt.target.value };
      //   });
    
      //   this.setState({ sequence_no: newShareholders });
      // };
    handleAddShareholder = (e) => {
      e.preventDefault();
      // let cDivs = this.state.customDiv;
      // cDivs.push('newDiv')
      // this.setState({customDiv: cDivs })
      this.setState({
        sequence_no: this.state.sequence_no.concat([{ sequence_no: "",
        redirect_url: "",status: "",image: ""}])
      });
    }
  
      render () { 
        const { formData,units,submitted} = this.state;
        this.handleAddShareholder = this.handleAddShareholder.bind(this);
        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/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="/morepromotions/listing">MorePromotions 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> <div>
            {/* {fields.map((field, idx) => { */}
              <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"
                  id="organization_id"
                  value={formData ? formData.organization_id:''}
                 
                >
                  {organization ?  organization.map((cell, i) => {
                  return(<option value={cell.id}>{cell.title}</option>)
                  }) : ''}     
                    
                </AvField>
                </AvGroup>
                </Col></Row>
                {this.state.sequence_no.map((cdiv, i) => 
                 
                  <div  key={cdiv} data-common-id="temp-`${i}`" > 
                <Row>
                <Col lg={6}>  
                <AvGroup>
                  <Label for="example">Sequence No</Label>
                  <AvInput type="number" name={"sequence_no"}   id="sequence_no" required value={formData ? formData.sequence_no:''}  />
                  <AvFeedback>Enter Sequence No..!</AvFeedback>
                  {/* {sequence_no?  sequence_no.map((cell, i) => {
                  return(<option value={cell.id}>{cell.sequence_no}</option>)
                  }) : ''} */}
                </AvGroup>
                </Col>
              
           <Col lg={6}>  
           <AvGroup>
                  <Label for="example">Redirect URL</Label>
                  <AvInput   name="redirect_url" id="redirect_url"  required value={formData ? formData.redirect_url:'' }   />
                  <AvFeedback>Enter Redirect URL..!</AvFeedback>
                </AvGroup>
           </Col></Row>
          
           <Row>
           <Col lg={6}>  
           <AvGroup>
                <Label for="example">Status</Label>
                <Input
                        type="select"
                        id="status"
                        name="status"
                        className="mb-3"
                      
                    >
                        <option value="1">Active</option>
                        <option value="2">In-Active</option>
                    </Input>
                </AvGroup>
            </Col>
           
            <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/>
           </Row>   
           </div>
           
      )}
         <button  class=" btn btn-outline-secondary" onClick={this.handleMeasure}   style={{float:'right ',margin:'auto'}}> Add More<i className="fas fa-plus"></i></button><br/><br/>
                <FormGroup>
             
                <Link to="/morepromotions/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>
                 
                   {/* {this.state.shareholders.map((shareholder, idx) => (
          <div className="shareholder">
            <input
              type="text"
              placeholder={`Shareholder #${idx + 1} name`}
              value={shareholder.name}
              onChange={this.handleShareholderNameChange(idx)}
            />
            
          </div>
        ))} */}
      
       </AvForm></div>
            {/* // })}  */}
            </CardBody>
          </Card>
        </Container>
        
      )
      }

    
}

    
 export default Validation;


