import React, { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { useFormik } from "formik";
import { useDispatch, useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
import {
  clearLoginErrors,
  fetchLogin,
} from "../../store/actions/login/loginActions";
import { selectLoginError } from "../../store/selectors/loginSelectors";
import { HOME_PAGE } from "../../constants/pages";
import { ReactComponent as Logo } from "../../assets/images/svg/logo-vertical.svg";
import { LoginPageContainer, LoginFormContainer } from "./Login.styled";
import loginValidation from "../../validations/loginValidation";
import loginInitialValues from "../../initialValues/loginInitialValues";
import LoginTitle from "./Title/LoginTitle";
import LoginDescription from "./Description/LoginDescription";
import EmailField from "./Fields/Email/EmailField";
import PasswordField from "./Fields/Password/PasswordField";
import ErrorMessage from "./ErrorMessage/ErrorMessage";
import ForgotPasswordLink from "./ForgotPasswordLink/ForgotPasswordLink";
import LoginButton from "./LoginButton/LoginButton";
import RegisterLink from "./RegisterLink/RegisterLink";

const Login = () => {
  const dispatch = useDispatch();
  const error = useSelector(selectLoginError);
  const history = useHistory();
  const passwordRef = useRef(null);
  const [passwordReset, setPasswordReseted] = useState(false);

  useEffect(() => {
    dispatch(clearLoginErrors());
  }, []);

  const handleApiResponseSuccess = () => {
    history.push({
      pathname: HOME_PAGE,
      state: {
        from: history.location.pathname,
      },
    });
  };

  useEffect(() => {
    if (passwordReset) {
      formik.setFieldValue("password", "");
    }
  }, [passwordReset]);

  const handleApiResponseError = () => {
    setPasswordReseted(true);
  };

  const handleSubmitForm = (e) => {
    e.preventDefault();
    console.log("handle submit form");
    if (!formik.isValid) {
      console.log("greska");
      formik.setFieldValue("password", "");
    }
    formik.handleSubmit(e);
  };

  const handleSubmit = (values) => {
    const { email, password } = values;
    if (!formik.isValid) {
      console.log("invalid");
    } else {
      dispatch(clearLoginErrors());
      dispatch(
        fetchLogin({
          email,
          password,
          handleApiResponseSuccess,
          handleApiResponseError,
        })
      );
      console.log(values);
    }
  };

  const formik = useFormik({
    initialValues: loginInitialValues,
    validationSchema: loginValidation,
    onSubmit: handleSubmit,
    validateOnBlur: true,
    enableReinitialize: true,
  });

  useEffect(() => {
    if (error) {
      if (formik.errors.email || formik.errors.password) {
        if (!passwordReset) {
          dispatch(clearLoginErrors());
        } else {
          setPasswordReseted(false);
        }
      }
    }
  }, [formik.errors.email, formik.errors.password]);

  return (
    <LoginPageContainer>
      <Logo />
      <LoginTitle />
      <LoginDescription />
      <LoginFormContainer component="form" onSubmit={handleSubmitForm}>
        <EmailField formik={formik} />
        <PasswordField formik={formik} ref={passwordRef} />
        <ErrorMessage formik={formik} />
        <ForgotPasswordLink />
        <LoginButton formik={formik} />
        <RegisterLink />
      </LoginFormContainer>
    </LoginPageContainer>
  );
};

Login.propTypes = {
  history: PropTypes.shape({
    replace: PropTypes.func,
    push: PropTypes.func,
    location: PropTypes.shape({
      pathname: PropTypes.string,
    }),
  }),
};
export default Login;
