import React, { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router";
import { NavLink } from "react-router-dom";

import { loading, selectIsLoading } from "@redux/loaderSlice";
import { auth, selectAuth, setUserInfo } from "@redux/outstaffingSlice";
import { setRole } from "@redux/roleSlice";

import { apiRequest } from "@api/request";

import { Loader } from "@components/Common/Loader/Loader";
import ModalErrorLogin from "@components/Modal/ModalErrorLogin/ModalErrorLogin";

import authImg from "assets/images/partnerProfile/authCandidateFormImg.png";

import "./authBlock.scss";

export const AuthBlock = ({ title, description, img, resetModal }) => {
  const dispatch = useDispatch();
  const ref = useRef();
  const navigate = useNavigate();

  const isAuth = useSelector(selectAuth);
  const isLoading = useSelector(selectIsLoading);

  const [error, setError] = useState(null);
  const [modalError, setModalError] = useState(false);

  useEffect(() => {
    if (!localStorage.getItem("auth_token")) {
      dispatch(auth(false));
    }
  }, []);

  useEffect(() => {
    if (isAuth) {
      navigate("/");
    }
  });

  const submitHandler = () => {
    let formData = new FormData(ref.current);
    if (!isLoading) {
      dispatch(loading(true));
      apiRequest("/user/login", {
        method: "POST",
        data: formData
      }).then((res) => {
        if (!res.access_token) {
          setError("Введены некорректные данные для входа");
          setModalError(true);
          dispatch(loading(false));
        } else {
          localStorage.setItem("auth_token", res.access_token);
          localStorage.setItem("id", res.id);
          localStorage.setItem("cardId", res.card_id);
          localStorage.setItem("role_status", res.status);
          localStorage.setItem(
            "access_token_expired_at",
            res.access_token_expired_at
          );
          dispatch(auth(true));
          dispatch(setUserInfo(res));
          dispatch(loading(false));
          dispatch(setRole("ROLE_PARTNER"));
        }
      });
    }
  };

  return (
    <div className="auth__wrapper">
      <div className="auth__info">
        {title && <h3>{title}</h3>}
        <img src={authImg} alt="img" />
        <p>{description}</p>
      </div>
      <form ref={ref} className="auth__form">
        <label htmlFor="login">Ваш e-mail</label>
        <input id="login" type="email" name="email" placeholder="E-mail" />

        <label htmlFor="password">Ваш пароль</label>
        <input
          id="password"
          type="password"
          name="password"
          placeholder="Пароль"
        />

        {error && (
          <div className="auth-box__form-error">
            <ModalErrorLogin
              active={modalError}
              setActive={setModalError}
              title={error}
            />
          </div>
        )}

        <div className="auth__form__buttons">
          <button
            className="auth-box__form-btn"
            onClick={(e) => {
              e.preventDefault();
              submitHandler();
            }}
          >
            {isLoading ? <Loader /> : "Войти"}
          </button>
          <NavLink to="/tracker-registration" className="auth__registration">
            Регистрация
          </NavLink>
        </div>
        <span className="auth__form__reset" onClick={() => resetModal(true)}>
          Восстановить пароль
        </span>
      </form>
      {img && <img src={img} alt="authImg" className="auth__img" />}
    </div>
  );
};

export default AuthBlock;
