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:'',
      units:'',
      formData:{
        title: '',
        quantity: '',
        weight: '',
        unit: '',
        sequence:'',
      },
      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/getMacroInfo/'+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/addMacro/`+this.state.user_id, {
                method: 'POST',
                body: JSON.stringify($('#pform').serializeArray()),
              }).then(response =>  response.json()).then((response) => {
                if(response == true){
                  toastr.success(
                    'Success',
                    "Nutrient Added Successfully..!",
                    this.options
                  )
                  this.props.history.push('/measures/macro_listing');
                }else{
                  toastr.error(
                    'Error',
                    "Nutrient not Added..!",
                    this.options
                  )
                }
              })
              .catch();
    });
  }

render () { 
  const { formData,units} = this.state;
  return(
  <Container fluid>
    <Header>
      <HeaderTitle>Add</HeaderTitle>

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        <BreadcrumbItem>
          <Link to="/measures/macro_listing">Macronutrients</Link>
        </BreadcrumbItem>
        <BreadcrumbItem active>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}>
           {/* 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.dimension}</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>
            <Button>Submit</Button>
          </FormGroup>
        </AvForm>
      </CardBody>
    </Card>
  </Container>
)
}
}

export default Validation;
