import React,{Component} from "react";
import { Link } from "react-router-dom";
import { Tabs,Tab } from 'react-bootstrap';
import {
  Breadcrumb,
  BreadcrumbItem,Row,Col,
  Card,
  CardBody,
  CardHeader,
  CardTitle,
  Container,
  Button,
  Label,Form,
  FormGroup,Input,
  InputGroup,
  InputGroupAddon,
  InputGroupText,
  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";
import { NONAME } from "dns";


class Validation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user_id:'0',
      units:'',
      source:'',
      groups:'',
      macro:'',
      micro:'',
      state:'',
      city:'',
      formData:{
        title: '',
        quantity: '',
        igroup: '',
        unit: '',
        source:'',
        macro:'',
        micro:'',
        state:'',
        city:''
      },
      submitted: false,
    }
    this.options = {
      timeOut: parseInt(5000),
      showCloseButton: true,
      progressBar: true,
      position: "top-right"
    };
  this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount(){
    const answer_array = this.props.location.pathname.split('/');
  
    if(answer_array['3']!=='0'){
      
        this.state.user_id = answer_array['3'];
        fetch(myConstClass.BASE_URL+'/ingredient/getIngredientInfo/'+answer_array['3'])
        .then(response => response.json())
        .then(response =>{
        this.setState({formData: response})
        
        if(this.state.formData.source=='2'){
          $('#source_div').show();
        }
      }).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))

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

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

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

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

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


  }

  handleStateChange = (event) => {

    //alert(event.target.value);
    if(event.target.value){

      const { formData } = this.state;
      formData['state'] = event.target.value;
      this.setState({ formData }); 
      //this.setState({state: event.target.value})
      fetch(myConstClass.BASE_URL+'/measures/getCity/'+event.target.value)
.then(response => response.json())
.then(response =>{
this.setState({city: response})
}).catch(err => console.log(err))
    }
      
    
  }

  handleChange = (event) => {

    //alert(event.target.value);
    if(event.target.name=='source' && event.target.value=='2'){
      $('#source_div').show();
    }
    if(event.target.name=='source' && event.target.value!='2'){
      $('#source_div').hide();
    }
    const { formData } = this.state;
    formData[event.target.name] = event.target.value;
    this.setState({ formData });   
    
  }

  handleNutrientChange=(event)=>{//alert($('[id^=macro]').val());
  var arr=[];
  $("input:text[name^='macro']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['macro'] = arr;
    this.setState({ formData });
  }

  handleMNutrientChange=(event)=>{
    var arr=[];
  $("input:text[name^='micro']").each(function(v){ 
    //alert($( this ).val() );
    arr.push($( this ).val());
  });
    const { formData } = this.state;
    formData['micro'] = arr;
    this.setState({ formData });
  }


  handleValidSubmit = (e) => {
    e.preventDefault();
    this.setState({ submitted: true }, () => {
      
        setTimeout(() => this.setState({ submitted: false }), 5000);
        fetch(myConstClass.BASE_URL+`/ingredient/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',
                    "Ingredient Added Successfully..!",
                    this.options
                  ) : toastr.success(
                    'Success',
                    "Ingredient Updated Successfully..!",
                    this.options
                  );
                  //alert('in');
                  this.props.history.push('/ingredients/listing');

                }else{
                  toastr.error(
                    'Error',
                    "Ingredient not Added..!",
                    this.options
                  )
                }
              })
              .catch();
    });
  }

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

      <Breadcrumb>
        <BreadcrumbItem>
          <Link to="/dashboard">Dashboard</Link>
        </BreadcrumbItem>
        <BreadcrumbItem>
          <Link to="/ingredients/listing">Ingredient</Link>
        </BreadcrumbItem>
        <BreadcrumbItem active>{(this.state.user_id =='0' ) ? 'Add' : 'Edit' }</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>
      
         <Form id="pform" onSubmit={this.handleValidSubmit}>
          {/* With AvGroup AvInput and AvFeedback to build your own */}
          <br/>
          <Row>
            <Col lg={6}>
            <InputGroup className="mb-3">
            <InputGroupAddon addonType="prepend">Name</InputGroupAddon>
            <Input name="title" value={this.state.formData.title} onChange={this.handleChange} required/>
            </InputGroup>
            </Col>
            <Col lg={6}>
            <InputGroup>
        <InputGroupAddon addonType="prepend" color="primary">
          Quantity
        </InputGroupAddon>
        <Input name="quantity" required value={this.state.formData.quantity} onChange={this.handleChange}/>
        <CustomInput required type="select" id="exampleCustomSelect" name="unit" value={this.state.formData.unit} onChange={this.handleChange}>
          {/* <option value="">Select...</option> */}
          {units ?  units.map((cell, i) => {
                 return(<option value={cell.id}>{cell.symbol}</option>)
            }) : ''}
        </CustomInput>
      </InputGroup>
            </Col>
           
          </Row>
          <Row>
    
            <Col lg={6}>
            <InputGroup>
            <InputGroupAddon addonType="prepend">
            Source
            </InputGroupAddon>       
            <CustomInput required type="select" id="exampleCustomSelect" name="source" value={this.state.formData.source} onChange={this.handleChange}>
              {/* <option value="">Select...</option> */}
              {source ?  source.map((cell, i) => {
                 return(<option value={cell.id}>{cell.title}</option>)
            }) : ''}
            </CustomInput>
            </InputGroup>
            </Col>
            <Col lg={6} >
            <InputGroup>
            <InputGroupAddon addonType="prepend">
            Group
            </InputGroupAddon>
       
            <CustomInput required type="select" id="exampleCustomSelect" name="igroup" value={this.state.formData.igroup} onChange={this.handleChange}>
              {/* <option value="">Select...</option> */}
              {groups ?  groups.map((cell, i) => {
                 return(<option value={cell.id}>{cell.title}</option>)
            }) : ''}
            </CustomInput>
            </InputGroup>
            </Col>
          </Row>
          <br/>
          <Row id="source_div" style={{display:'none'}}>    
            <Col lg={6}>
            <InputGroup>
            <InputGroupAddon addonType="prepend">
            State
            </InputGroupAddon>       
            <CustomInput required type="select" id="exampleCustomSelect" name="state" value={this.state.formData.state} onChange={this.handleStateChange}>
              {/* <option value="">Select...</option> */}
              {state ?  state.map((cell1, i1) => {
                 return(<option value={cell1.id}>{cell1.name}</option>)
            }) : ''}
            </CustomInput>
            </InputGroup>
            </Col>
            <Col lg={6} >
            <InputGroup>
            <InputGroupAddon addonType="prepend">
            City
            </InputGroupAddon>
       
            <CustomInput required type="select" id="exampleCustomSelect" name="city" value={this.state.formData.city} onChange={this.handleChange} >
              {/* <option value="">Select...</option> */}
              {city ?  city.map((cell2, i2) => {
                 return(<option value={cell2.id}>{cell2.name}</option>)
            }) : ''}
            </CustomInput>
            </InputGroup>
            </Col>
          </Row>
          <br/>
          <Tabs defaultActiveKey="home" id="uncontrolled-tab-example">
            <Tab eventKey="home" title="Nutritional Value as per Quantity Selected">
            <br/>
          <Row>
          <Col lg={12}><h4><center>Macronutrients</center></h4></Col>
          </Row>
          <Row>
          {macro ?  macro.map((cell, i) => {
                 return(<Col lg={6} style={{marginBottom : '1.0rem'}}>
                  <InputGroup>
              <InputGroupAddon addonType="prepend" color="primary">
                {cell.title}
              </InputGroupAddon>
              <Input type="number" name={"macro_"+cell.uid} value={formData.macro ? formData.macro[i] :''} onChange={this.handleNutrientChange}/>
              <InputGroupAddon addonType="prepend" color="primary">
                
                {cell.unit}
                </InputGroupAddon>
            </InputGroup>
                  </Col>)
            }) : ''}
          </Row>
          <br/>

          <Row>
          <Col lg={12}><h4><center>Micronutrients</center></h4></Col>
          </Row>
          <Row>
          {micro ?  micro.map((cell, i) => {
                 return(<Col lg={6} style={{marginBottom : '1.0rem'}}>
                  <InputGroup>
              <InputGroupAddon addonType="prepend" color="primary">
                {cell.title}
              </InputGroupAddon>
              <Input type="number" name={"micro_"+cell.uid} value={formData.micro ? formData.micro[i] :''} onChange={this.handleMNutrientChange}/>
              <InputGroupAddon addonType="prepend" color="primary">
                
                {cell.unit}
                </InputGroupAddon>
            </InputGroup>
                  </Col>)
            }) : ''}
          </Row>
          </Tab>
          <Tab eventKey="common" title="Common Measures">

</Tab>
</Tabs>
          <br/>
          <Row>
          <Col lg={12}>
          <FormGroup>
          <Link to="/ingredients/listing" style={{margin:"0rem 1.5rem 1.5rem 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>
          </Col>
          </Row>
       </Form>
      
      
      </CardBody>
    </Card>
  </Container>
)
}
}

export default Validation;
