import * as React from 'react'
import { Field, WrappedFieldProps } from 'redux-form'

export interface OwnProps {
  name: string,
  type?: string,
  label?: string,
  help?: string,
}

interface P extends OwnProps, WrappedFieldProps {}

class BootstrapField extends React.PureComponent<P, {}> {
  
  renderInput() {
    // cherry-pick or unload the garbage trunk, as you like
    const props = {
      // you can add onFocus or what else
      onChange: this.props.input.handleChange,
      value: this.props.input.value,
      id: this.props.name, // for labels, yo
      type: this.props.type,
    }
    // you'll need a bit more to handle checkboxes and radios
    // that's a story for another time
    return props.type === 'textarea' ?
      <textarea {...props} /> :
    props.type === 'select' ?
      <select {...props}>
        {props.children}
      </select> :
    props.children ?
      React.cloneElement(props.children as any, props) :
    <input {...props} />
  }
  
  render() {
    return <div className="form-group">
      {this.props.label && <label htmlFor={this.props.name} className="control-label">
        {this.props.label}
      </label>}
      <div className="input-group">{
        this.renderInput()
      }</div>
      {this.props.help && <small className="text-muted">{this.props.help}</small>}
    </div>
  }
}

// create a RF Field typed with the props we want in our bootstrap Field
// and export with RF6's inversion of control® already included
// to get a nicer API in our forms
const MyCustomField = Field as new () => Field<OwnProps>
export default class extends React.PureComponent<OwnProps, {}> {
  render = () => <MyCustomField component={BootstrapField} {...this.props} />
}
