import React from "react";
import "../Auth.css";
import CInput from "../../../components/CInput";
import { Link, useNavigate } from "react-router-dom";
import CButton from "../../../components/CButton";
import AuthHeader from "../AuthHeader";
import { useTranslation } from "react-i18next";
import { useForm } from "react-hook-form";
import { authLogin } from "../../../stores/slices/authSlice";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../../stores/store";
import { TG_USER_ID } from "../../../constants/constants";
import { useAuth } from "../../../contexts/AuthContext/useAuth";
import TheCybernanny from "../../../assets/images/TheCybernanny.png";

interface ILoginFormData {
  login: string;
  password: string;
}

const Login: React.FC = () => {
  const { t } = useTranslation();
  const { setAuthenticated } = useAuth();
  const navigate = useNavigate();
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ILoginFormData>();

  const dispatch = useAppDispatch();
  const { loadingLogin, errorLogin } = useAppSelector(
    (state: RootState) => state.auth
  );

  const onSubmit = async (data: ILoginFormData) => {
    try {
      const result = await dispatch(authLogin(data));
      if (authLogin.fulfilled.match(result)) {
        const token = result.payload.token;
        localStorage.setItem(`token-${TG_USER_ID}`, token);
        setAuthenticated(true);
        navigate("/home");
      }
    } catch (e) {
      console.error("Unexpected error in login form", e);
    }
  };

  return (
    <div className="wrapper login">
      <AuthHeader />

      <div className="auth__logo">
        <img src={TheCybernanny} alt="TheCybernanny" />
      </div>

      <h2>{t("auth.entrance")}</h2>

      <form className="auth__form" onSubmit={handleSubmit(onSubmit)}>
        <CInput
          label={`${t("auth.login")}`}
          placeholder={`${t("auth.loginPlaceholder")}`}
          {...register("login", { required: t("error.requiredField") })}
          error={errors.login?.message as string}
        />
        <CInput
          label={`${t("auth.password")}`}
          placeholder={`${t("auth.passwordPlaceholder")}`}
          type="password"
          {...register("password", { required: t("error.requiredField") })}
          error={errors.password?.message as string}
        />

        <div className="auth__form__links">
          <p>
            {t("auth.noAccount")}{" "}
            <Link to={"/auth/register"}>{t("auth.register")}</Link>
          </p>
          <p>
            {t("auth.forgetPassword")}{" "}
            <Link to={"/auth/recover"}>{t("auth.recover")}</Link>
          </p>
        </div>

        {errorLogin && <p className="text-danger text-center">{errorLogin}</p>}

        <CButton title={`${t("button.continue")}`} isLoading={loadingLogin} />
      </form>
    </div>
  );
};

export default Login;
