import React, {useState} from "react";
import { Field, reduxForm } from 'redux-form';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import { toast } from 'react-toastify';
import style from "./authForm.module.sass";
import FancyInput from "../../inputs/FansyInput";
import {sendFormDataAuth} from "../../../actions/actionCreator";

const AuthForm = (props) => {
    const [counterForInputPrivateKey, setCounter] = useState(0);

    const authHandler = () => {
      props.sendDataFormAuth(props.auth.values);
    };


    if(props.token && !props.isFetching) {
        props.history.push("/");
    }
    if(counterForInputPrivateKey == 20) {
        toast.success("((= Поздравляем, вы в режиме администратора");
    }


    return(
      <div className={style.mainContainerForm}>
          <Field
              name={'email'}
              type={'text'}
              isValidation={false}
              component={FancyInput}
              label={'Введите пожалуйста почту котрую вы использовали при регистрации'}
          />
          <Field
              name={'password'}
              type={'password'}
              isValidation={false}
              onClick={() => setCounter(counterForInputPrivateKey + 1)}
              component={FancyInput}
              label={'Введите пожалуйста пароль'}
          />
          {
              counterForInputPrivateKey > 20 && (
                  <Field
                      name={'adminPrivateKey'}
                      type={'password'}
                      isValidation={false}
                      component={FancyInput}
                      label={'Введите пожалуйста приватный ключ'}
                  />
              )
          }
          <div className={style.buttonAuth} onClick={authHandler}>
              {props.isFetching ? <p>Подождите...</p>:<p>Войти</p>}
          </div>

      </div>
    );
};

const mapStateToProps = state => {
    const {auth} = state.form;
    const {token, isFetching, error} = state.signUpReducers;

    return {
        auth, token, isFetching, error
    }
};

const mapDispatchToProps = dispatch => ({
    sendDataFormAuth: authData => dispatch(sendFormDataAuth(authData))
});



export default reduxForm({
    form: 'auth'
})(withRouter(connect(mapStateToProps, mapDispatchToProps)(AuthForm)));