import * as React from 'react'
import BootstrapField from './BootstrapField'
import { reduxForm, getFormValues, FormProps, FieldArray } from 'redux-form'
import { connect } from 'react-redux'
import { AppState, Settings, DispatchProps } from './types'

interface StateProps {
  formValues: Settings | undefined,
}

interface OwnProps extends FormProps<Settings, AppState> {
  handleSave: (settings: Settings) => void,
}

interface P extends OwnProps, StateProps, DispatchProps {}

// notice that this.props.handleSubmit! and props.form! need a bang "!" when using strictNullChecks
// reason is complicated, you can have a look here: https://github.com/erikras/redux-form/pull/1318#issuecomment-231590672
class SettingsForm extends React.PureComponent<P, {}> {

  render() {
    // this.props.handleSubmit => redux form's handler
    // this.props.handleSave => our controller's handler
    return <form onSubmit={this.props.handleSubmit!(this.props.handleSave)}>
      <legend>Settings</legend>
      <BootstrapField name="sex" label="Sex" type="select">
        <option key="" value="">""</option>
        <option key="m" value="m">Male</option>
        <option key="f" value="f">Female</option>
        <option key="o" value="o">Other, complicated, will not disclose</option>
      </BootstrapField>
      <BootstrapField name="firstName" label="First name"/>
      <BootstrapField name="lastName" label="Last name" help="Ask your family if not sure" />
      <BootstrapField name="phone" label="Phone" type="phone" />
      <div className="btn-toolbar">
        <button type="submit" className="btn btn-primary" disabled={this.props.submitting || this.props.pristine}>
          Process
        </button>
      </div>
    </form>
  }
}

// if you need additional stuff from app's state, you totally can connect your form
const mapStateToProps = (state: AppState, props: OwnProps): StateProps => ({
  formValues: getFormValues<Settings>(props.form!)(state),
})

export default connect<OwnProps, StateProps, DispatchProps>(mapStateToProps)(reduxForm({})(SettingsForm))
