import React, { Component } from 'react'
import ItemTypeV from './ItemTypeV'
import ItemTemplateV from './ItemTemplateV'
import axios from 'axios'
import { Redirect } from 'react-router-dom';

const types = ['procurement']
const subtypes = {
  'procurement': ['ITB', 'RFP', 'RTQ', 'BW', 'SS', 'Extensions', 'Legacy', 'Access', 'Contract Modification', 'Five-year Pool Extensions', 'OTR', 'Emergency', 'Rejection', 'Supplement'],
  'default': ['Select a value!']
}

class ItemTypeC extends Component {
  constructor (props) {
    super(props)
    this.state = {
      itemtype: 'default',
      subtype: 'default',
      name: '',
      title: '',
      contract: '',
      assignee: '',
      priority: '',
      deadline: '',
      sections: [],
      filledSections: []
    }
  }

  /* Handle change of inputs */
  onChangeType = (event) => {
    this.setState({
      itemtype: event.target.value
    })
  }

  onChangeSubtype = (event) => {
    this.setState({
      subtype: event.target.value
    })
  }

  onChangeName = (event) => {
    this.setState({
      name: event.target.value
    })
  }

  onChangeTitle = (event) => {
    this.setState({
      title: event.target.value
    })
  }

  onChangeContract = (event) => {
    this.setState({
      contract: event.target.value
    })
  }

  onChangeAssignee = (event) => {
    this.setState({
      assignee: event.target.value
    })
  }

  onChangePriority = (event) => {
    this.setState({
      priority: event.target.value
    })
  }

  onChangeDeadline = (event) => {
    this.setState({
      deadline: event.target.value
    })
  }

  onChangeGeneric = (i, event) => {
    let valuesOfSections = [...this.state.filledSections]
    valuesOfSections[i] = event.target.value
    this.setState({
      filledSections: valuesOfSections
    })
  }

  /* Handle onsubmits */
  // This would be the first submit. Initially youll be presented with two drop downs and a submit button
  onSubmitType = (event) => {
    event.preventDefault()
    let url = 'http://localhost:4000/api/item/create/' + this.state.itemtype + '/' + this.state.subtype
    axios.get(url)
      .then(res => {
        this.setState({
          sections: res.data.tpsections,
          filledSections: res.data.tpsections
        })
      })
  }

  // ADDED userdID so that it can the submit of the document is dynamically created based on the user that is signed in.
  // **** ENDED HERE *****
  // how can you use this payload maybe to pass these states as parameters to the buildPDF that youll create eventually.
  // start seeing this piece of the code again
  onSubmitItem = (event) => {
    event.preventDefault()
    let userID = sessionStorage.getItem('userID')
    let dataobject = {}
    for (let i = 0; i < this.state.filledSections.length; i++) {
      dataobject[this.state.sections[i]] = this.state.filledSections[i]
    }
    let payload = {
      mtuser: userID,
      mttype: this.state.itemtype,
      mtsubtype: this.state.subtype,
      mtname: this.state.name,
      mttitle: this.state.title,
      mtcontract: this.state.contract,
      mtassignee: this.state.assignee,
      mtpriority: this.state.priority,
      mtdeadline: this.state.deadline,
      mtsections: dataobject
    }
    //console.log(dataobject)
    let url = 'http://localhost:4000/api/item/create/submit'
    axios.post(url, payload)
      .then(res => {
        this.setState({
          success: 'Item with contract ' + payload.mtcontract + ' successfully created.',

        })
      })
      .catch(err => {
        console.log(err.response.data.Error);
        this.setState({
          error: err.response.data.Error
        })
      })
  }

  render () {
    if(this.state && this.state.success) {
      return (
        <Redirect
          to={{
            pathname:"/success",
            state: { success: this.state.success}
          }}
        />
      )
    }
    if(this.state && this.state.error) {
      return (
        <Redirect
          to={{
            pathname: "/error",
            state: { error: this.state.error, referrer: this.props.location.pathname }
          }}
        />
      )
    }
    if (this.state.sections.length !== 0) {
      return (
        <ItemTemplateV type={this.state.itemtype}
          subtype={this.state.subtype}
          sections={this.state.sections}
          name={this.state.name}
          title={this.state.title}
          contract={this.state.contract}
          assignee={this.state.assignee}
          priority={this.state.priority}
          deadline={this.state.deadline}
          generic={this.onChangeGeneric}
          changeName={this.onChangeName}
          changeTitle={this.onChangeTitle}
          changeContract={this.onChangeContract}
          changeAssignee={this.onChangeAssignee}
          changePriority={this.onChangePriority}
          changeDeadline={this.onChangeDeadline}
          filledSections={this.state.filledSections}
          submit={this.onSubmitItem} />
      )
    } else {
      return (
        <div>
          <ItemTypeV types={types}
            subtypes={subtypes}
            currentType={this.state.itemtype}
            onChangeType={this.onChangeType}
            onChangeSubtype={this.onChangeSubtype}
            submit={this.onSubmitType} />
        </div>
      )
    }
  }
}

export default ItemTypeC
