import React,{PureComponent} from "react";
import { Link } from "react-router-dom";

import {
  Breadcrumb,
  BreadcrumbItem,Row,Col,
  Card,
  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.state = {
      user_id:'0',
      units:'',
      formData:{
        title: '',
        quantity: '',
        weight: '',
        unit: '',
        sequence:'',
      },
      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
    };
  
  }

  componentDidMount(){
    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+'/measures/getInfo/'+answer_array['3'])
        .then(response => response.json())
        .then(response =>{
        this.setState({formData: response})
      }).catch(err => console.log(err))

    }

    fetch(myConstClass.BASE_URL+'/measures/getUnits/')
      .then(response => response.json())
      .then(response =>{
      this.setState({units: response})
    }).catch(err => console.log(err))

  }

 
  handleValidSubmit = () => {
 
    this.setState({ submitted: true }, () => {
      
        setTimeout(() => this.setState({ submitted: false }), 5000);
        fetch(myConstClass.BASE_URL+`/measures/add/`+this.state.user_id, {
                method: 'POST',
                body: JSON.stringify($('#pform').serializeArray()),
              }).then(response =>  response.json()).then((response) => {
                if(response == true){
                  (this.state.user_id =='0' ) ?
                  toastr.success(
                    'Success',
                    "Measures Added Successfully..!",
                    this.options
                  ) : toastr.success(
                    'Success',
                    "Measures Updated Successfully..!",
                    this.options
                  );

                  this.props.history.push('/measures/listing');
                }else{
                  toastr.error(
                    'Error',
                    "Measures not Added..!",
                    this.options
                  )
                }
              })
              .catch();
     });
  }

render () { 
  const { formData,units,submitted} = this.state;
  return(
  <Container fluid>
    <Header>
      <HeaderTitle>{(this.state.user_id !=='0' ) ? 'Edit' : 'Add' }</HeaderTitle>

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        <BreadcrumbItem>
          <Link to="/measures/listing">Measures</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>
            <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">Quantity</Label>
            <AvInput name="quantity" id="example" required value={formData ? formData.quantity:''}/>
            <AvFeedback>Enter Quantity!</AvFeedback>
          </AvGroup>
          </Col>
          </Row>
          <Row>
            <Col lg={6}>
          <AvGroup>
            <Label for="example">Weight</Label>
            <AvInput name="weight" id="example" required value={formData ? formData.weight:''}/>
            <AvFeedback>Enter Weight</AvFeedback>
          </AvGroup>
          </Col>
          <Col lg={6}>
           {/* With select and AvField */}
           <AvField
            type="select"
            name="unit"
            label="Unit"
            value={formData ? formData.unit:''}
          //  helpMessage="Idk, this is an example. Deal with it!"
          >
            {units ?  units.map((cell, i) => {
            return(<option value={cell.id}>{cell.name}({cell.symbol})</option>)
            }) : ''}
            
  
          </AvField>
          </Col>
          </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="/measures/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;
