import React, { Component } from "react";
import { connect } from "react-redux";

import {
  clearUserRequestError,
  clearUserRequestSuccess,
  setFormSocialInsuranceNumber
} from "../../actions/user/reducer.actions";
import { createProviderRequest } from "../../actions/user/saga.actions";
import ProviderFormView from "./ProviderFormView";

class InitializeProviderForm extends Component {
  componentWillMount() {
    this.props.dispatch(clearUserRequestError());
    this.props.dispatch(clearUserRequestSuccess());
  }

  changeSocialInsuranceNumber = event => {
    this.props.dispatch(setFormSocialInsuranceNumber(event.target.value));
  }

  onSubmitProvider = event => {
    event.preventDefault();
    const { socialInsuranceNumber } = this.props;
    this.props.dispatch(
      createProviderRequest({ sin: socialInsuranceNumber })
    );
  };

  render() {
    const {
      isSendingUserRequest,
      userRequestError,
      userRequestSuccess,
      socialInsuranceNumber
    } = this.props;
    return (
      <ProviderFormView
        isSendingUserRequest={isSendingUserRequest}
        userRequestError={userRequestError}
        userRequestSuccess={userRequestSuccess}
        socialInsuranceNumber={socialInsuranceNumber}
        changeSocialInsuranceNumber={this.changeSocialInsuranceNumber}
        onSubmitProvider={this.onSubmitProvider}
      />
    );
  }
}

function mapStateToProps(state) {
  return { ...state.user };
}

export default connect(mapStateToProps)(InitializeProviderForm);
