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

import {
  clearUserRequestError,
  clearUserRequestSuccess,
  setFormBusinessNumber
} from "../../actions/user/reducer.actions";
import { updateClientRequest } from "../../actions/user/saga.actions";
import ClientFormView from "./ClientFormView";

class EditClientForm extends Component {
  changeBusinessNumber = event => {
    this.props.dispatch(setFormBusinessNumber(event.target.value));
    this.props.dispatch(clearUserRequestError());
    this.props.dispatch(clearUserRequestSuccess());
  };

  onSubmitClient = event => {
    event.preventDefault();
    const { selfUser, businessNumber } = this.props;
    const businessNumberVal =
      businessNumber || (selfUser.client || {}).business_number;
    this.props.dispatch(
      updateClientRequest({
        username: selfUser.username,
        business_number: businessNumberVal
      })
    );
  };

  render() {
    const {
      isSendingUserRequest,
      userRequestError,
      userRequestSuccess,
      businessNumber,
      selfUser
    } = this.props;
    const businessNumberVal =
      businessNumber || (selfUser.client || {}).business_number;
    return (
      <ClientFormView
        isSendingUserRequest={isSendingUserRequest}
        userRequestError={userRequestError}
        userRequestSuccess={userRequestSuccess}
        businessNumber={businessNumberVal}
        changeBusinessNumber={this.changeBusinessNumber}
        onSubmitClient={this.onSubmitClient}
      />
    );
  }
}

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

export default connect(mapStateToProps)(EditClientForm);
